// salon24.2.0 
//
// pre alfa and probably not working at all it will burn your hardware then eat you alive!!!! 
// (it now seems to be less evil but this is only to TRAP YOU!!!!!)
//
// --------------------------------------------------------------------
//
// This is a Greasemonkey user script.
//
// To install, you need Greasemonkey: http://greasemonkey.mozdev.org/
// Then restart Firefox and revisit this script.
// Under Tools, there will be a new menu item to "Install User Script".
// Accept the default configuration and install.
//
// To uninstall, go to Tools/Manage User Scripts,
// select "salon24", and click Uninstall.
//
// for opera you need: http://www.howtocreate.co.uk/operaStuff/userjs/aagmfunctions.js
//
// --------------------------------------------------------------------
//
// ff gid: 938f37a3-0235-473a-b563-6bf4399a5593
//
// ==UserScript==
// @name          Salon24 (2.0)
// @namespace     simple.unknown.evil.namespace.truly.evil.this.is.not.a.joke
// @description   go eeeaaaasssyyyyyyyyy
// @include       *salon24.pl*
// @version			0.5
// ==/UserScript==
$ver = "0.5";
//
// created with help from Jan Słupski. follow at juljas dot net
//
// for a list of functions go there: http://juljas.net/s24/faq/#greasemonkey 
//

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	var ret = {};
	ret.left = curleft;
	ret.top = curtop;
	return ret;
}

function hookEvent(element, eventName, callback) {
	if(typeof(element)=="string")
		element = document.getElementById(element);
	if(element==null)
		return;
	if(element.addEventListener) {
		element.addEventListener(eventName, callback, false);
	} else if(element.attachEvent)
		element.attachEvent("on"+eventName, callback);
}

function unhookEvent(element, eventName, callback) {
	if(typeof(element)=="string")
		element = document.getElementById(element);
	if(element==null)
		return;
	if(element.removeEventListener)
		element.removeEventListener(eventName, callback, false); else if(element.detachEvent)
			element.detachEvent("on"+eventName, callback);
}

function cancelEvent(e) {
	e = e ? e : window.event;
	if(e.stopPropagation)
		e.stopPropagation();
	if(e.preventDefault)
		e.preventDefault();
	e.cancelBubble = true;
	e.cancel = true;
	e.returnValue = false;
	return false;
}

function Position(x, y) {
	this.X = x;
	this.Y = y;

	this.Add = function(val) {
		var newPos = new Position(this.X, this.Y);
		if(val!=null) {
			if(!isNaN(val.X))
				newPos.X += val.X;
			if(!isNaN(val.Y))
				newPos.Y += val.Y
		}
		return newPos;
	}

	this.Subtract = function(val) {
		var newPos = new Position(this.X, this.Y);
		if(val!=null) {
			if(!isNaN(val.X))
				newPos.X -= val.X;
			if(!isNaN(val.Y))
				newPos.Y -= val.Y
		}
		return newPos;
	}

	this.Min = function(val) {
		var newPos = new Position(this.X, this.Y)
			if(val==null)
				return newPos;

		if(!isNaN(val.X) && this.X>val.X)
			newPos.X = val.X;
		if(!isNaN(val.Y) && this.Y>val.Y)
			newPos.Y = val.Y;

		return newPos;
	}

	this.Max = function(val) {
		var newPos = new Position(this.X, this.Y)
			if(val==null)
				return newPos;

		if(!isNaN(val.X) && this.X<val.X)
			newPos.X = val.X;
		if(!isNaN(val.Y) && this.Y<val.Y)
			newPos.Y = val.Y;

		return newPos;
	}

	this.Bound = function(lower, upper) {
		var newPos = this.Max(lower);
		return newPos.Min(upper);
	}

	this.Check = function() {
		var newPos = new Position(this.X, this.Y);
		if(isNaN(newPos.X))
			newPos.X = 0;
		if(isNaN(newPos.Y))
			newPos.Y = 0;
		return newPos;
	}

	this.Apply = function(element) {
		if(typeof(element)=="string")
			element = document.getElementById(element);
		if(element==null)
			return;
		if(!isNaN(this.X))
			element.style.left = this.X+'px';
		if(!isNaN(this.Y))
			element.style.top = this.Y+'px';
	}
}

function absoluteCursorPostion(eventObj) {
	eventObj = eventObj ? eventObj : window.event;

	if(isNaN(window.scrollX))
		return new Position(eventObj.clientX+document.documentElement.scrollLeft+document.body.scrollLeft, eventObj.clientY+document.documentElement.scrollTop+document.body.scrollTop); else
			return new Position(eventObj.clientX+window.scrollX, eventObj.clientY+window.scrollY);
}

function dragObject(element, attachElement, lowerBound, upperBound, startCallback, moveCallback, endCallback, attachLater) {
	if(typeof(element)=="string")
		element = document.getElementById(element);
	if(element==null)
		return;

	if(lowerBound!=null && upperBound!=null) {
		var temp = lowerBound.Min(upperBound);
		upperBound = lowerBound.Max(upperBound);
		lowerBound = temp;
	}

	var cursorStartPos = null;
	var elementStartPos = null;
	var dragging = false;
	var listening = false;
	var disposed = false;

	function dragStart(eventObj) {
		if(dragging || !listening || disposed) return;
		dragging = true;

		if(startCallback!=null)
			startCallback(eventObj, element);

		cursorStartPos = absoluteCursorPostion(eventObj);

		elementStartPos = new Position(parseInt(element.style.left), parseInt(element.style.top));

		elementStartPos = elementStartPos.Check();

		hookEvent(document, "mousemove", dragGo);
		hookEvent(document, "mouseup", dragStopHook);

		return cancelEvent(eventObj);
	}

	function dragGo(eventObj) {
		if(!dragging || disposed) return;

		var newPos = absoluteCursorPostion(eventObj);
		newPos = newPos.Add(elementStartPos).Subtract(cursorStartPos);
		newPos = newPos.Bound(lowerBound, upperBound)
			newPos.Apply(element);
		if(moveCallback!=null)
			moveCallback(newPos, element);

		return cancelEvent(eventObj);
	}

	function dragStopHook(eventObj) {
		dragStop();
		return cancelEvent(eventObj);
	}

	function dragStop() {
		if(!dragging || disposed) return;
		unhookEvent(document, "mousemove", dragGo);
		unhookEvent(document, "mouseup", dragStopHook);
		cursorStartPos = null;
		elementStartPos = null;
		if(endCallback!=null)
			endCallback(element);
		dragging = false;
	}

	this.Dispose = function() {
		if(disposed) return;
		this.StopListening(true);
		element = null;
		attachElement = null
			lowerBound = null;
		upperBound = null;
		startCallback = null;
		moveCallback = null
			endCallback = null;
		disposed = true;
	}

	this.StartListening = function() {
		if(listening || disposed) return;
		listening = true;
		hookEvent(attachElement, "mousedown", dragStart);
	}

	this.StopListening = function(stopCurrentDragging) {
		if(!listening || disposed) return;
		unhookEvent(attachElement, "mousedown", dragStart);
		listening = false;

		if(stopCurrentDragging && dragging)
			dragStop();
	}

	this.IsDragging = function() {
		return dragging;
	}
	this.IsListening = function() {
		return listening;
	}
	this.IsDisposed = function() {
		return disposed;
	}

	if(typeof(attachElement)=="string")
		attachElement = document.getElementById(attachElement);
	if(attachElement==null)
		attachElement = element;

	if(!attachLater)
		this.StartListening();
}

// =====================================================================
// =====================================================================
// =====================================================================
// =====================================================================
// =====================================================================
// =====================================================================
// =====================================================================
// =====================================================================
//

function simpleDecode(str) {

	var ret = str.replace(/\<br\>/gi,'');
	ret = ret.replace(/\<a[^>]*\>([^<]*)\<\/a\>/gi, "$1");
	ret = ret.replace(/&amp;/gi, "&");
	ret = ret.replace(/&lt;/gi, "<");
	ret = ret.replace(/&gt;/gi, ">");
	return ret;
}

// configuration
$comment_window_height = 'param_cmt_window_height';
$troll_level = 'param_troll_level';
$supertroll_level = 'super_troll_level';
$before_nick = 'param_before_nick' ;
$after_quoted_text = 'param_after_quoted_text';
$quote_char = 'char used to quoting';
$reload_comments = 'reload_comments_in_background';
$track_comments = 'track_comments_in_background';
$do_urlize_comments = "urlize_comments";
$tracked_link_list = 'tracked link list';
$reload_tracked_comments = 'reload tracked comment every x s';
$comment_draft = 'my last comment draft';
$post_draft = 'my last post draft';
$sg_post_list = 'first post on sg';
$sg_new_count = 'number of new posts on sg';
$sg_first_title = 'first title on sg';
$reload_sg_data = 'checking sg';
$sg_first_title_length = 'how long is first title';
$subscripction_title_length='how long should be subscripcion title';

$key_refresh_comments = '$key_refresh_comments';
$key_refresh_subscriptions = '$key_refresh_subscriptions';
$key_refresh_sginfo = '$key_refresh_sginfo';
$key_toggle_subscriptions = '$key_toggle_subscriptions';
$key_toggle_ui = '$key_toggle_ui';
$key_scroll_top = '$key_scroll_top';
$key_scroll_bottom = '$key_scroll_bottom';

$how_to_open_window = "howtoopenwindow";

// global variables
$trueWindow = undefined; // helps with opera lack of unsafeWindow
$id_regexp = new RegExp('.*/([^,]*).*');
$window_active = false;

$current_response = undefined;
$current_comment = undefined;

$X='~`^!`][' // :>

$store = {
	login : "my login stored",
	my_last_post_cmts : "comments number under my last post",
	my_last_unread_cmts : "unread comments number under my last post",
	tracked_new_replies_total : "tracked enw replies total",
	set : function(name, value) {
		//GM_log(name + " + " + value);
		GM_setValue(name, value?value:0);
		//GM_log("done");
	},
	setPrivate: function(name, value) {
		GM_setValue(GM_getValue($store.login) + "_" + name, value?value:0);
	},
	getPrivate : function(name) {
		return GM_getValue(GM_getValue($store.login) + "_" + name);
	}
};

$comments = {	
	parsed:{},
	html:undefined,
	htmlList:undefined
};

//script state 
$state = {
	post_id : undefined,
	comments_updating: 0,
	comments: 0,
	comments_update_time: new Date(),
	reply_url : undefined,
	post_title : undefined,
	post_url : undefined
}

$loginInfo = {
	login: 0,
	my_last_post_id: 0,
	author_post_replies: 0
};

//ui window(s) holder
$ui = {
	mode: GM_getValue('ui_mode', 0),
	trackedmode: GM_getValue('ui_trackedmode', 0),
	main:undefined,
	div:undefined,
	config: undefined,
	small : {
		comm:undefined,
		comm_text:undefined,
		ablog:undefined,
		comm_img:undefined,
		ablog_link:undefined,
		ablog_text:undefined,
		trep: undefined,
		trep_text: undefined,
		track:undefined,
		track_icon:undefined,
		more: undefined
	},
	full : {
		tracked_list : undefined,
		comm:undefined,
		comm_text1:undefined,
		comm_text2:undefined,
		ablog:undefined,
		ablog_link:undefined,
		track:undefined,
		track_icon:undefined,
		less: undefined
	},
	blocker : undefined
};

//media library
$media = {
	sgicon: "data:image/png,%89PNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%20%00%00%00%0B%08%02%00%00%00%91s%18V%00%00%00%01sRGB%00%AE%CE%1C%E9%00%00%00%09pHYs%00%00%0Da%00%00%0D%B0%01%A4%07%96p%00%00%00%07tIME%07%D8%07%1A%0F'%1F%E3%AC%A7%A4%00%00%00%19tEXtComment%00Created%20with%20GIMPW%81%0E%17%00%00%03NIDAT8%CB%85RMHcg%14%BD%DF%7B%2F%99%A4%F1%C5i2%23%8D%11%CB%A0%06%2B%1AS%A6%03%E6Ij!%B8RW%22O%17%0ABp%D1%11w%8A.c%05%5Bp5%9D%8D%E8%A6%A0T%D0E%B1%3F%D9H7RP%82%0B'%14%15gl'%3FCfQ%26%9A%E6%E5%BD%2F%EF~%B7%8BG%BBk%7BV%F7r%E0%1E%EE9%87%AD%AC%AC%C0%BF%20%91H%F8%DE%F3%1D%FD%F4%E3%A3B%D1k%9A%15%7Fs%F9%C1%FD%EE%DF%0A5%AF%E7%E1%1F%95b%E8a%F1%83%10%00%C1%7FB%E1%9C%FF%B3%10%11c%CC%19%88(%12%89%04%1F%04_%3C%7F%FE%D1%EF%AF%DF(%AEh%B1T%EDx%F4a%BEX%91%25%15%11%AC%FA%AB%FB%EF3%F6%3F%0AJSS%93%AE%EB%C1%60%F0%FA%FA%FA%E0%E0%60dd%A4%AF%AF%AFZ%AD%EE%ED%ED!%22%A1p%BF%AB%10%B0%17%5EO%A8%FA%A7%EB%5D%05%80~%BDw%2Fj%9A%D4htuu%C5%B5x0%184M%F3%F4%F4%F4%E4%E4%C49%DA%DA%DA%3A%3A%3AZ%AB%D5vww%A5%C1%C1%C1%EE%EE%EE%5C.%A7i%9A%A6i%C9d%B2P(%B4%B5%B5%25%12%09!%04%11%D9%B6M%40%8A%2C%03%40%83s%22%90e%09%18%20%E2%A7%9F%0D%F9%7C%BE%9B%9B%9Bp8%3C55%D5%DE%DEnY%16%11MOO%F7%F6%F6vvv%1A%86%A1%20%22c%AC%5C.%5B%96%05%00%9C%F3%AB%AB%AB%9E%9E%1E%B7%DB-%84%00%20%81%08%006%22%00%08D%06%80B%10%91%10%F4%EC%D9%D77%AF%5E2%C6fggu%5Doii%C9%E5r%BA%AE%5B%96U%AF%D7%01%C04M%E9%E8%E8%88s%9EL%26%17%16%16%B6%B7%B7%D3%E9%F4%D0%D0%90%D7%EB%15B%08!%88%18%0A%01%00%B6m%03%80%8D%82%18%20%22%10%01%D0%9BR%C9%EF%F7%AB%AA%1A%0E%87%89%E8%F2%F22%16%8B%0D%0C%0C%AC%AD%AD!%22%11Y%96%25%5D%5C%5C%AC%AF%AF777oll%F4%F7%F7%A7%D3%E9r%B9%5C%AB%D5%1C%7F%08%E8%AD%10%12%C0%13%8B%03%B0%B7%C2%06%00D%24%00%02%20!%1A%8DF%3C%1E%D74%ED%F8%F88%9F%CF%A7R%A9%C3%C3C%97%CB%C5%18%93%24)%10%08HsssKKK%3B%3B%3B%AA%AA%C6b1%97%CB%95%CDfm%DBv%3E%00%A2_%40%7C%87%8D%97%0D%EB%1Ba%15%09%801%81%08DD%C2%E2%3C%1E%8F%CF%CF%CF%9F%9D%9D%AD%AE%AE%86B!UUu%5D%DF%DC%DC%F4%F9%7C%81%40%60qqQAD%8F%C7%E3%A4%EFT%B6%A3%A3%C3%09%80%88T%BF%FF%8B%2F%BFBB%22x%C2%A4%9F%F7%BE%85%B3s%14%82%18%90%A0%B1%B1%B1%A7O%3F%BF%BB%BB%CBf%B3%E3%E3%E3%D5jurr%92%88dY%DE%DA%DA2MsyyY%C9d2%C3%C3%C3%A9T%AAT*e2%99%89%89%89H%24r%7B%7B%8B%88%B5Z%8Ds%1E%FB8%E6%C83%C6N%7F%F8%BEN%C2%12X%97X%9D%E8%F1'%8F%0D%C3P%14eff%861v~~%BE%BF%BF%EF%98c%18%86a%18%F9%7C%9EE%A3Q%00P%14%85s%EEpN%9E%B2%2C%13%91%D31%22r%04%18%03aq%D9%E5%166%02%23%C9%ED%11%C2v(%00%90%24%C9q%FF%EF%82%90%2C%CB%7F%01(%AB%EBX%BE%059%05%00%00%00%00IEND%AEB%60%82",
	sgicon24: "data:image/png,%89PNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%18%00%00%00%08%08%02%00%00%00l%C3%A84%00%00%00%01sRGB%00%AE%CE%1C%E9%00%00%00%09pHYs%00%00%0Da%00%00%0D%B0%01%A4%07%96p%00%00%00%07tIME%07%D8%07%1A%0F'%0B%F9vs%D9%00%00%00%19tEXtComment%00Created%20with%20GIMPW%81%0E%17%00%00%02%09IDAT(%CFu%91%BFk%1Aq%18%87%DF%F3%CE%CB%19%5B%91B%B2%A8%1D%F4%0C%1A%7Fb%A4%D6Y%5D%E2%EA%A0%88K%24%9B%BB%C9%E2%D4%90%BF%20%9B%AB%14%EAPq%EB%20%0EBiI%0AE%CA%0D%A7T%8A%16%D4%18%95%DEq%9A%F3%BE%DF%B7CC%A1C%9F%ED%F3%0C%9F%E5a...%E0_x%9E%2F%14%0A%1F%DE5%1Dw_%18%C4%C1K%A7%7F%F4c%C7r%8F%7B%E6o%5E%11%FE%83%89%E3%B8x%3C%EEv%BBu%5D%0F%06%83%D1h%94%10%E2%F3%F9%0E%A6%D3%FD%F9%1C%1E%1E%0E%86%DF%0F%EF%17%CAj%F9b%3A%13%04K(%14%0A%87%C3f%B3y%B3%D9l6%1BA%10%8E%8E%8E%10%91%CBf%B36%9B%CD%EB%F5v%3A%9Dd2%A9%AA*%CF%F3%00%40%B6%5B%C3d2L%2C%DDn%01A1s%87%DB%C7%7C%3E%BFX%DC%7B%3C%9Et%3A%5D%AB%D5X%96-%97%CB%0E%87%A3V%ABq%9A%A6%D9%ED%F6n%B7%3B%18%0CX%96%F5%FB%FDOG%84P%A4%942%04%E8%D3%A4xyy%B9%DB%E9%A9T%AAR%A9%E8%BA%5E*%95%86%C3%A1%D3%E9%D44%CDT%AF%D7y%9Ew%B9%5C%93%C9%24%91H%F0%3Co%18%06%00%A8%84%EE%13%FA%8C%10%95P%60%C00%08%02%12%C3%B0Z%AD%A7%A7%A7%BD%5E%2F%10%08X%AD%D6v%BB%8D%88%84%10%D3%D9%D9Y%BF%DF%17E1%93%C9%ACV%2BY%96%09!%00%F0%95%81.%D2%CFd%F7%89%01%00%86%10%03%11Y%8E%ABV%AB%CB%E5%F2%FA%FA%3A%16%8B%1D%1F%1F_%5D%5D%01%40%A5R%81V%AB%25%CB%B2%AE%EB%8DFC%D3%B4%D9l%D6l6%11QUUEQ%14Ey%7Bs%F31%FE%FA%CDI%FC%FD%C9%AB%DB%DB%3BD%94%24I%92%A4%F3%F3%F3H%24R%2C%16)%A5%B9%5C%8EI%26%93%91Hd%BD%5E%8FF%A3P(4%9F%CF%11%D1f%B3%FD%ED%BA%9C%CF%CC%93%9F%BFXV%20%F4y0(%08%7B%7F%FCx%3CVU%D5b%B1%88%A2(%CB%F2o%7F%5E%0F%8A%AC%B3aS%00%00%00%00IEND%AEB%60%82",
	commenticon: "data:image/gif,GIF89a%0D%00%0D%00%D50%00%B6%B5%B6%86%87%85%FE%FE%FF%BB%BF%BC%97%94%95%E0%E0%E0%F4%F4%F3%B6%B3%B2%89%8C%8A%FC%FD%FD%F7%F7%F8%B4%B1%B3%FD%FE%FC%BD%BD%BB%FD%FC%FC%DC%DD%DC%CC%CD%CC%BF%C2%C3%AC%AC%AC%8D%8E%8C%C0%C0%C0%F8%F9%F8%9F%9F%9C%C0%BF%BD%FC%FC%FE%FD%FF%FE%F2%F1%F2%C8%CA%CA%98%9A%96%A5%A6%A6%E1%E2%E3%DE%DD%DF%FE%FF%FF%A8%A8%A9%D3%D4%D4%F3%F2%F3%B7%B6%B6%D1%D0%D0%BA%BD%BC%B3%B7%B6%BF%C0%C1%91%8F%90%86%84%85%FC%FC%FD%9C%97%99%F9%F9%F9%FE%FE%FE%BE%BF%BB%FF%FF%FF%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00!%F9%04%01%00%000%00%2C%00%00%00%00%0D%00%0D%00%00%06m%40%98p(%7C%BD%88H%18%E4%D5%DA%24a%00%CB%23%D329%89%1F%C4d%E0p%B5ZGa%A1!%EA%04N%8E%8C%11%E6%91D*%AE%11%2B0x%40%84%14%83%C0%05%8Aw%26%16C%17%0A%09%0C%2B%7D%22%08%00C%07%18%04)%0C.%15%0D%1FD%0B%1A%24%04%09%02%11%05H!(%1A%18%0A%06%12H%1C*!%0B%07%17%14%1EH%25%1CODA%00%3B",
	plusicon: "data:image/gif,GIF89a%0D%00%09%00%A1%02%00%B0%AF%AF%FF%FF%FF%B3II%B3II!%FE%15Created%20with%20The%20GIMP%00!%F9%04%01%0A%00%02%00%2C%00%00%00%00%0D%00%09%00%00%02%12%14%8E%09%A6%ED%E1%14%8C%20XKk%3Es7F%09%05%00%3B",
	minusicon: "data:image/gif,GIF89a%0D%00%09%00%A1%02%00%B0%AF%AF%FF%FF%FF%B3II%B3II!%FE%15Created%20with%20The%20GIMP%00!%F9%04%01%0A%00%02%00%2C%00%00%00%00%0D%00%09%00%00%02%0E%14%8E%09%A6%ED%0F%5D%983%DA%1B%19%14%05%00%3B",
	homeicon: "data:image/gif,GIF89a%0D%00%0D%00%A1%00%00%9F%9F%9C%FF%FF%FF%9F%9F%9C%9F%9F%9C%21%F9%04%01%0A%00%02%00%2C%00%00%00%00%0D%00%0D%00%00%02%24%94%0F%A7%0A%2D%B9%5E%9B%71%DA%65%33%CA%3A%81%00%86%81%67%7C%CD%68%32%E8%0A%95%6B%D8%3E%2F%18%73%54%84%0B%05%00%3B",
	watchicon: "data:image/gif,GIF89a%0D%00%0D%00%C2%00%00%9F%9F%9C%D0%D0%D0%D9%D9%D9%DF%DE%DE%F1%F1%F1%FF%FF%FF%9F%9F%9C%9F%9F%9C%21%F9%04%01%0A%00%07%00%2C%00%00%00%00%0D%00%0D%00%00%03%2F%78%BA%DC%FE%D0%05%40%41%68%13%94%5D%E8%3D%83%56%10%82%40%6C%C0%70%88%85%40%09%1C%B0%72%2E%00%A3%A0%48%9A%A8%7A%64%9C%8E%05%53%19%46%8E%C7%04%00%3B",
	configicon:"data:image/gif,GIF89a%40%00%09%00%A1%01%00%B0%AF%AF%FF%FF%FF%FF%FF%FF%FF%FF%FF%21%F9%04%01%0A%00%02%00%2C%00%00%00%00%40%00%09%00%00%02%4C%0C%8E%A9%CB%ED%CF%CC%91%10%51%70%AB%CE%8B%3B%E3%69%22%04%5A%52%80%5A%49%3A%A5%27%C6%C2%E7%35%73%F1%8B%C7%D8%C4%E3%FD%AF%28%ED%82%43%5F%91%D8%E2%ED%68%B0%E1%6A%69%53%B2%5E%4E%59%D5%9A%11%4E%8F%A1%D1%47%E7%55%46%C2%E4%72%23%50%00%00%3B",
	untrackedicon:"data:image/gif,GIF89a%0E%00%0D%00%D5%3F%00%E7%E7%E6%E9%EA%E9%D5%D5%D6%E7%E8%E6%B5%B4%B6%B4%B3%B6%DE%DD%DD%AD%AB%AB%BA%BA%BB%F7%F7%F7%F2%F1%F3%E8%E9%E9%FB%FA%FB%A7%A6%A9%B6%B5%B7%B5%B5%B5%B4%B5%B5%FE%FF%FF%AF%B0%AF%AB%AA%A6%D0%CF%D0%B4%B4%B1%E5%E6%E6%FC%FC%FC%A8%AA%A8%FD%FD%FD%E8%E9%E7%B1%B0%AF%F5%F6%F5%BD%BD%BC%F0%EE%F1%A2%A3%A3%F7%F6%F5%94%93%93%ED%EE%ED%B4%B4%B5%E6%E2%E4%D8%D7%D6%C6%C5%C5%E3%E3%E3%CE%D0%CE%B3%B2%B5%EF%F1%EF%D1%CF%CF%EA%EC%EB%ED%EB%ED%B3%B4%B3%F6%F5%F5%D8%D8%D7%BB%BB%BB%E5%E5%E6%DF%E0%E0%9A%9A%9B%DB%DB%DA%A7%A9%AA%EF%F1%F0%AA%AB%A8%BB%BA%B9%B6%B4%B7%D1%D0%CE%C8%C8%C8%FB%FB%FA%FC%FB%FA%FF%FF%FF!%F9%04%01%00%00%3F%00%2C%00%00%00%00%0E%00%0D%00%00%06%82%C0%9FpH%2C%0Aw%1D%9E%92%D7%D9%11)%98Z%8B%24%12-N3%0C%E5%B7%9B%F8%BE%BD%B0%AF%C7%F0Mv%95K%26E(%14%08%3A%82%23s%A9%C4%22%96A%60%BF%08h4%16%111%12%3E%0A)%23q%0E%8A%0E%0A%3E%12%0F%1B%09%0C%03%00%95%94%00%09%1B%0F%3F%0D6%257%1C%1C%2F%0A%0B*%1E6%06B(%07%0D%07%0E.%26%2C%0909E2%02%2B%02%08%1F%06%20%10FE41%10%22%C0E8!A%00%3B",
	trackedicon:"data:image/gif,GIF89a%0E%00%0D%00%A5%2C%00%94%93%93%A7%A6%A9%A7%A9%AA%AD%AB%AB%B1%B0%AF%B3%B2%B5%B4%B3%B6%B3%B4%B3%B4%B4%B5%B5%B4%B6%B6%B4%B7%B6%B5%B7%C6%C5%C56%FFW%D8%D7%D6%D8%D8%D7%DB%DB%DA%DE%DD%DD%DF%E0%E0%E6%E2%E4%E3%E3%E3%E5%E6%E6%E7%E7%E6%E7%E8%E6%E8%E9%E7%E8%E9%E9%E9%EA%E9%EA%EC%EB%ED%EB%ED%ED%EE%ED%F0%EE%F1%EF%F1%EF%EF%F1%F0%F2%F1%F3%F6%F5%F5%F5%F6%F5%F7%F6%F5%F7%F7%F7%FB%FA%FB%FB%FB%FA%FC%FB%FA%FC%FC%FC%FD%FD%FD%FE%FF%FF%FF%FF%FF%FF%FF%FF%FF%FF%FF%FF%FF%FF%FF%FF%FF%FF%FF%FF%FF%FF%FF%FF%FF%FF%FF%FF%FF%FF%FF%FF%FF%FF%FF%FF%FF%FF%FF%FF%FF%FF%FF%FF%FF%FF%FF%FF%FF%FF%FF%FF%FF%FF%FF%FF%FF%FF%FF%FF%FF%FF!%FE%11Created%20with%20GIMP%00%2C%00%00%00%00%0E%00%0D%00%00%06k%40%96pH%2C%0A%1B%C8%24%92%88%84p%26%9DN%86%22Y6%00%A8%ECi%8B%3A%99P%C9%94%AA%900%18%12%8A%C4B%95B%AE*%17%8D%3C%A3%C1%60*%2B%24*T%40%A4%17%80%0B!%60%0D%04%25%26%17%16%8A%89%16%25V%02%0E%20%23%23%22!%19%1F%1E%0D%11G%0D%01%03%0B%07%0C%1B%25%0F%0DEJI%24%A6FLH%1D%AC%A7%0DA%00%3B",
	throbbericon :"data:image/gif,GIF89a%0D%00%0D%00%84%1E%00%00%00%00%08%73%BD%0C%7B%BD%18%7B%C6%1C%84%C6%35%90%CA%46%9C%CE%5A%A2%D3%6B%AF%D8%8B%BF%E1%B5%B5%B5%A0%CE%E7%B5%D6%EF%BD%BD%BD%BD%DE%EF%C6%C6%C6%CE%CE%CE%D6%D6%D6%DE%DE%DE%CA%E2%F3%D6%E7%F7%DE%EF%F7%E7%E7%E7%E7%EF%F7%E7%F7%FF%EF%EF%EF%EF%F7%FF%F7%F7%F7%F7%F7%FF%F7%FF%FF%FF%FF%FF%FF%FF%FF%21%FF%0B%4E%45%54%53%43%41%50%45%32%2E%30%03%01%00%00%00%21%F9%04%05%06%00%1F%00%2C%00%00%00%00%0D%00%0D%00%00%05%59%E0%27%7E%54%82%2C%D5%38%56%46%E0%BA%87%B6%0A%81%40%04%37%CE%89%6D%51%25%81%C4%E4%86%20%D5%2E%1E%60%C2%33%71%69%16%01%84%27%19%9C%B6%18%88%2A%75%E9%C9%26%80%52%0F%E3%C0%B0%06%18%94%E3%74%DD%0C%C8%7A%15%F6%20%2A%AA%D0%02%06%44%4B%37%BA%EC%5F%08%32%2A%24%0B%27%29%23%21%00%21%F9%04%05%06%00%1F%00%2C%00%00%00%00%0D%00%0D%00%00%05%47%E0%27%7E%D3%92%7C%DA%A8%AE%22%37%5E%C4%17%14%47%21%16%E9%EA%71%44%30%BC%2A%4F%22%60%70%88%2E%AB%8A%4C%69%73%9C%10%A2%83%4A%BA%58%7C%A4%9F%0B%C2%35%72%4C%64%2C%91%C0%33%8A%75%59%E6%AB%ED%B3%0E%47%91%2B%E4%69%15%02%00%21%F9%04%05%06%00%1F%00%2C%00%00%00%00%0D%00%0D%00%00%05%3F%E0%27%7E%D7%58%8D%63%89%8A%EA%77%8A%C6%CA%AD%A2%E7%4D%C2%38%7D%C1%E8%39%85%9E%C0%23%3A%B0%8C%01%02%0D%25%48%D0%10%28%55%81%F5%C9%AD%1C%BC%56%61%27%E2%A6%46%D3%98%48%63%5A%CE%56%5E%F2%28%04%00%21%F9%04%05%06%00%1F%00%2C%00%00%00%00%0D%00%0D%00%00%05%48%E0%27%7E%54%82%8C%E8%57%A5%A2%86%0A%1F%8C%18%22%C1%A6%B6%48%C5%A8%E7%4D%9F%80%EB%73%FA%38%12%C8%84%8D%71%4A%88%9C%81%68%E0%83%44%31%0E%D8%C3%72%77%03%7E%86%A2%D5%4D%05%FB%18%8A%1F%02%67%74%61%21%C0%A3%DD%49%2C%0A%01%00%21%F9%04%05%06%00%1F%00%2C%00%00%00%00%0D%00%0D%00%00%05%49%E0%27%7E%D3%92%7C%DA%A8%AE%22%37%5E%C4%17%14%C7%58%A4%6C%7E%E5%9F%23%EE%AA%0B%E2%E2%F1%14%7A%27%84%A8%26%48%78%6A%8B%C5%A7%F6%D9%05%02%84%A3%63%22%53%39%0A%81%8F%C0%33%8A%8D%1C%82%95%79%7A%FC%B4%79%53%60%F0%73%5A%85%00%00%21%F9%04%05%06%00%1F%00%2C%00%00%00%00%0D%00%0D%00%00%05%40%E0%27%7E%D7%58%8D%63%89%8A%EA%77%8A%C6%57%8C%DC%BA%0E%E3%F4%05%B6%2E%78%A2%03%AA%F6%89%D9%44%09%E0%0A%21%AA%F0%2A%4A%D2%47%30%4A%04%0C%8E%5D%AB%A0%E3%10%78%A8%ED%4A%63%3A%12%51%3A%11%79%14%02%00%21%F9%04%05%06%00%1F%00%2C%00%00%00%00%0D%00%0D%00%00%05%45%E0%27%7E%D4%87%8C%E8%57%A5%A2%86%0A%1F%8C%18%22%C1%A6%B6%58%C2%77%E0%9A%22%47%C2%81%62%9C%12%22%E4%E8%A8%4C%7E%12%9E%0F%8D%51%1A%25%02%D0%49%0B%55%B9%26%26%03%2E%8F%10%C8%11%38%A3%0B%0B%F1%43%95%4E%AB%51%08%00%21%F9%04%05%06%00%1F%00%2C%00%00%00%00%0D%00%0D%00%00%05%46%E0%27%7E%D3%97%7C%DA%A8%AE%22%37%5E%C4%17%14%C7%58%A4%6C%7E%E5%9F%23%EE%AA%0B%02%57%E8%9D%10%A2%1A%F2%53%5B%2C%98%BD%80%00%27%72%94%02%9F%42%60%E1%19%09%BA%A2%C1%CC%E3%F1%AD%62%D9%43%31%CB%1B%1D%80%41%13%2B%04%00%21%F9%04%05%06%00%1F%00%2C%00%00%00%00%0D%00%0D%00%00%05%41%E0%27%7E%D7%58%8D%63%89%8A%EA%77%8A%C6%57%8C%DC%BA%0E%E3%F4%05%B6%2E%78%A2%83%E8%54%FB%C4%50%9C%04%CF%06%23%F0%10%A3%19%49%14%30%50%80%1F%C7%AE%45%98%60%75%A8%16%6C%A4%31%31%8B%28%F0%A7%3C%0A%01%00%21%F9%04%05%06%00%1F%00%2C%00%00%00%00%0D%00%0D%00%00%05%49%E0%27%7E%54%82%8C%E8%57%A5%A2%86%0A%1F%8C%18%22%C1%A6%B6%48%C5%F7%17%68%89%0F%E1%40%3C%30%50%8C%53%60%29%0A%7E%4E%CE%42%62%9A%70%88%68%8C%9D%E0%E2%F1%8C%26%AD%51%61%D5%AB%C0%3E%86%53%8D%33%BA%B0%10%AE%D4%EE%44%16%85%00%00%21%F9%04%05%06%00%1F%00%2C%00%00%00%00%0D%00%0D%00%00%05%48%E0%27%7E%D3%92%7C%DA%A8%AE%22%37%5E%C4%17%14%C7%58%A4%63%CC%8A%97%1C%18%94%91%83%B7%F8%18%08%81%00%02%57%F8%38%4E%08%CE%E9%83%10%D5%8A%9F%83%C7%53%89%AA%1C%13%D9%EE%23%F0%E4%BE%2C%5D%B6%F9%61%8F%B3%BD%55%6F%AA%0A%01%00%21%F9%04%01%06%00%1F%00%2C%00%00%00%00%0D%00%0D%00%00%05%41%E0%27%7E%D7%58%8D%63%89%8A%EA%77%A2%C5%C8%AD%41%2C%0E%E3%C4%16%C1%22%EA%02%8F%E8%E0%71%7C%04%23%C3%CA%E3%39%AC%50%08%D6%47%23%B2%95%90%2B%63%A0%55%D0%FD%56%DC%8F%52%44%15%BD%56%B3%95%77%8A%0A%01%00%3B"
};

$iso=[
	'%B1', //ą
	'%B6', //ś
	'%E6', //ć
	'%F1', //ń
	'%BF', //ż
	'%B3', //ł
	'%F3', //ó
	'%BC', //ź
	'%EA', //ę
	'%A1', //Ą
	'%A6', //Ś
	'%C6', //Ć
	'%D1', //Ń
	'%AF', //Ż
	'%A3', //Ł
	'%D3', //Ó
	'%AC', //Ź
	'%CA'  //Ę
	]

$utf8 = [
	new RegExp('%C4%85', 'g'), //ą
	new RegExp('%C5%9B', 'g'), //ś
	new RegExp('%C4%87', 'g'), //ć
	new RegExp('%C5%84', 'g'), //ń
	new RegExp('%C5%BC', 'g'), //ż
	new RegExp('%C5%82', 'g'), //ł
	new RegExp('%C3%B3', 'g'), //ó
	new RegExp('%C5%BA', 'g'), //ź
	new RegExp('%C4%99', 'g'), //ę
	new RegExp('%C4%84', 'g'), //Ą
	new RegExp('%C5%9A', 'g'), //Ś
	new RegExp('%C4%86', 'g'), //Ć
	new RegExp('%C5%83', 'g'), //Ń
	new RegExp('%C5%BB', 'g'), //Ż
	new RegExp('%C5%81', 'g'), //Ł
	new RegExp('%C3%93', 'g'), //Ó
	new RegExp('%C5%B9', 'g'), //Ź
	new RegExp('%C4%98', 'g')  //Ę
]

function addGlobalStyle(css) {
    var head, style;
    head = document.getElementsByTagName('head')[0];
    if (!head) { return; }
    style = document.createElement('style');
    style.type = 'text/css';
    style.innerHTML = css;
    head.appendChild(style);
}



// i don't really like this but since it's not valid xml
// and iframe sucks ass this is the quickest way.
function parseHtmlResponse(response) {

	response = response.split('\n');
	var res = [];
	for(var i=0;i<response.length;i++) {
		if(response[i].match('<body.*>')) {
			i++;
			break;
		}
	}

	for(;i<response.length;i++) {
		if(response[i].match('</body>')) break;
		res[res.length] = response[i];
	}

	res = res.join('\n');
	var div = document.createElement('div');
	div.innerHTML = res;

	return div;
}


// i have no idea whatsoever why da hell i have to use this shitty function
// but no other idea how to solve encoding problem so far...
// is there really no native change encoding in js ..?
function fixEncoding(str) {
	for(var i=0;i<$utf8.length;i++) str = str.replace($utf8[i], $iso[i]);
	return str;
}

function fixSymbols(aa) {
	var bb = '';
	for(i=0; i<aa.length; i++) {
		if(aa.charCodeAt(i)>127) {
			bb += '&#' + aa.charCodeAt(i) + ';';
		} else {
			bb += aa.charAt(i);
		}
	}
	return bb;
}

function addEvent(obj, evType, fn) {
	if(!obj) return false;
	if (obj.addEventListener) {
		obj.addEventListener(evType, fn, false);
		return true;
	} else if (obj.attachEvent) {
		var r = obj.attachEvent("on" + evType, fn);
		return r;
	} else {
		return false;
	}
}

function getElementsByCondition(condition,container,tag) {
	container = container||document
		tag = tag||'*'
		var all = container.all||container.getElementsByTagName(tag)
		var arr = []
		for(var k=0;k<all.length;k++) {
			var elm = all[k]
				if(condition(elm,k)) arr[arr.length] = elm
		}
	return arr
} 

function getElementsByClass(classname, container, tag) {
	var re = new RegExp('\\b'+classname+'\\b')
	return getElementsByCondition(function(el){if(el.className && el.className.match(re)) return el;}, container, tag)
}

function getElementByClass(classname, container, tag) {
	var re = new RegExp('\\b'+classname+'\\b')
	var ret = getElementsByCondition(function(el){if(el.className && el.className.match(re)) return el;}, container, tag)
	if(ret.length>0) return ret[0];
}

function toggleHidden(el) {
	if(el) el.style.display == none ? el.style.display='block' : el.style.display = 'none';
}

function loadPage(address, onLoad, onError) {
	GM_xmlhttpRequest({
		method: 'GET',
		url: address,
		headers: {
			'Cookie': document.cookie,
			'Accept-Charset': 'ISO-8859-2',
		},
		onload: function(responseDetails) {
			if(responseDetails.status != 200) {
				hideLoadingInfo();
				GM_log('status:\n' + responseDetails.status);
				GM_log('statustext:\n'+responseDetails.statusText);
				GM_log('responsetext:\n'+responseDetails.responseText);
				return;
			}	

			if(onLoad) onLoad(responseDetails);
		},
		onerror: function(responseDetails) {
			GM_log('status:\n' + responseDetails.status);
			GM_log('statustext:\n'+responseDetails.statusText);
			GM_log('responsetext:\n'+responseDetails.responseText);
			hideLoadingInfo();
			if(onError) onError(responseDetails);
		}
	});
}

function parseComment(cmt) {

	var comment = {
			htmlElement: cmt,
			body : getElementByClass('comment_body', cmt),
			title : getElementByClass('comment_title', cmt),
			author : getElementByClass('comment_author', cmt),
			date : getElementByClass('comment_date', cmt),
			cc : getElementByClass('author_comment_count', cmt),
			bc : getElementByClass('author_blog_count', cmt),
			link : getElementByClass('link_to_comment', cmt),
			dlink : getElementByClass('link_to_delete', cmt),
			hidden : false
	};

	var nicks = getElementsByClass('ut_user_.*', comment.author);
	for(var i=0;i<nicks.length;i++) {
		if(nicks[i].innerHTML!='') {
			var nick = nicks[i];
			break;
		}
	}

	var b = nick.getElementsByTagName('b');
	if(b.length>0 && b[0] != undefined) nick = b[0]

	comment.nick = nick.innerHTML;

	var num = comment.dlink.href.replace($id_regexp, "$1");
	var id = comment.nick+$X+num;
	comment.htmlElement.id = id;
	comment.id = id;
	comment.number = num;

	return comment;
}

function refreshComments() {
	if(!$state.post_id) return;

	showLoadingInfo();
	loadPage(document.location.href, updateComments);	
}

function updateComments(responseDetails) {
	var response = parseHtmlResponse(responseDetails.responseText);
	var new_commentlist = getElementByClass('comments_list', response);
	if(!new_commentlist) {
		hideLoadingInfo();
		return;
	}
	var new_comments = new_commentlist.getElementsByTagName('li');

	var existing_comments= {};
	var comments_to_append = [];
	var urlize = getParam($do_urlize_comments, "nie") == "tak";

	for(var i=0;i<new_comments.length;i++) {
		var new_comment = new_comments[i];
		var parsed_comment = parseComment(new_comment);
		var old_comment = $comments.parsed[parsed_comment.id];

		if(!old_comment) {
			comments_to_append[comments_to_append.length] = new_comment;
			setupComment(parsed_comment, urlize);
			$comments.parsed[parsed_comment.id] = parsed_comment;
		}
		existing_comments[parsed_comment.id] = parsed_comment;
	}

	// cannot be done in previous for because this modifies new_comments list as it removes 
	// child when it's appended to a different list.
	for(var i=0;i<comments_to_append.length;i++) {
		$comments.htmlList.appendChild(comments_to_append[i]);
	}

	for (var i in $comments.parsed) {
		var cmt = $comments.parsed[i];
		if(!existing_comments[cmt.id]) {
			$comments.htmlList.removeChild(cmt.htmlElement);
			delete $comments.parsed[i];
		}
	}

	$state.comments = new_comments.length;
	$state.comments_update_time = new Date();

	rememberCommentsOnThisPage();

	hideLoadingInfo();
}

function parseComment(cmt) {

	var comment = {
			htmlElement: cmt,
			body : getElementByClass('comment_body', cmt),
			title : getElementByClass('comment_title', cmt),
			author : getElementByClass('comment_author', cmt),
			date : getElementByClass('comment_date', cmt),
			cc : getElementByClass('author_comment_count', cmt),
			bc : getElementByClass('author_blog_count', cmt),
			link : getElementByClass('link_to_comment', cmt),
			dlink : getElementByClass('link_to_delete', cmt),
			hidden : false
	};

	var nicks = getElementsByClass('ut_user_.*', comment.author);
	for(var i=0;i<nicks.length;i++) {
		if(nicks[i].innerHTML!='') {
			var nick = nicks[i];
			break;
		}
	}

	var b = nick.getElementsByTagName('b');
	if(b.length>0 && b[0] != undefined) nick = b[0]

	comment.nick = nick.innerHTML;

	var num = comment.dlink.href.replace($id_regexp, "$1");
	var id = comment.nick+$X+num;
	comment.htmlElement.id = id;
	comment.id = id;
	comment.number = num;

	return comment;
};

function toggleBlacklisted(nick) {
	if(isBlacklisted(nick)) {
		whitelistNick(nick);
	} else {
		blacklistNick(nick);
	}
}

function blacklistNick(nick) {
	if(!isBlacklisted(nick)) {
		var blacklist = unescape(GM_getValue('blacklist', ''));
		blacklist = blacklist + nick + '\t';
		$store.set('blacklist', escape(blacklist));
	}
	applyToAllComments(displayComment);
};

function whitelistNick(nick) {
	var blacklist = unescape(GM_getValue('blacklist', '')).split('\t');
	var res = []
		for(var i=0;i<blacklist.length;i++) {
			if (blacklist[i] != nick) res[res.length] = blacklist[i];
		}
	$store.set('blacklist', escape(res.join('\t')))
	applyToAllComments(displayComment);
}

function isBlacklisted(nick) {
	var blacklist = unescape(GM_getValue('blacklist', '')).split('\t');
	for(var i=0;i<blacklist.length;i++) {
		if(blacklist[i]==nick) {
			return true;
		}
	}
	return false;
}

function toggleDisplay(comment) {
	if(comment.hidden) {
		displayNormal(comment);
	} else {
		displayBlacklisted(comment);
	}

	if(isBlacklisted(comment.nick)) {
		comment.htmlElement.style.background = '#f3f3f3';
		comment.cc.style.color='red';
		comment.blacklist.innerHTML = 'przestań ignorować';
	}
}

function displayBlacklisted(comment) {
	var votes = getVotes(comment.nick);
	var super_level = getParam($supertroll_level, '-10');

	comment.htmlElement.style.background = '#f3f3f3';
	comment.cc.style.color='red';
	comment.blacklist.innerHTML = 'przestań ignorować';

	if(votes <= super_level) {
	 	if(!comment.superTrollElement.parentNode) {
			comment.htmlElement.parentNode.replaceChild(comment.superTrollElement, comment.htmlElement);
	 	}
	} else {
		comment.body.style.display='none';
		comment.title.style.display='none';
	}
	comment.hidden = true;
}

function displayNormal(comment) {
	if(!comment.htmlElement.parentNode) {
		comment.superTrollElement.parentNode.replaceChild(comment.htmlElement, comment.superTrollElement);
	}
	comment.htmlElement.style.display='block';
	comment.body.style.display='block';
	comment.title.style.display='block';
	comment.htmlElement.style.background = 'white';
	comment.cc.style.color='gray';
	comment.blacklist.innerHTML = 'ignoruj autora';
	comment.hidden = false;
}

function gatherComments() {
	var cmts = getElementByClass('comments_list');
	if (!cmts) return;

	$comments.htmlList = cmts;
	var list = cmts.getElementsByTagName('li');


	for(var i=0;i<list.length;i++) {
		rememberComment(list[i], i);
	}
	$comments.size = list.length;

	$state.comments = list.length;
}

function rememberComment(c, idx) {
	var comment = parseComment(c);

	$comments.parsed[comment.id] = comment;
	return comment;
}

function applyToAllComments(operation) {
	if(!$comments || !$comments.parsed) return;
	for(var i in $comments.parsed) {
		operation($comments.parsed[i], i);
	}
}

function getVotes(nick) {
	return GM_getValue(nick+'_votes', 0);
}

function voteForAuthor(nick, vote) {
	var votes = vote ? getVotes(nick) + 1 : getVotes(nick) - 1;
	$store.set(nick+'_votes', votes);
	var troll_level = getParam($troll_level, '-5');
	if(votes<=troll_level) {
		blacklistNick(nick);
	}
	else {
		whitelistNick(nick);
	}
	applyToAllComments(displayComment);
}

function enick(e) {
	e.preventDefault();
	return e.target.id.split($X)[1];
}

function ecomment(e) {
	e.preventDefault();
	var tmp = e.target.id.split($X);
	return $comments.parsed[[tmp[1],tmp[2]].join($X)];
}

function createDefaultInput(width, id, deflt) {
	var input = document.createElement('input');
	input.type = 'text';
	input.style.width = width;
	input.value = getParam(id, deflt);
	//does not work - why?
	input.style.borderTop = input.style.borderRight = input.style.borderLeft = 'none';
	input.style.borderBottom = '1px solid gray';
	//input.style.background = 'black';
	//input.style.color = 'red';
	input.id = id;

	addEvent(input, 'change', function(e) {setParam(id, input.value)});

	return input;
}

function getParam(name, def) {
	var param = GM_getValue($X+name);
	if(param == undefined) {
		$store.set($X+name, def);
		return def;
	}
	return param;
}

function setParam(name, val) {
	$store.set($X+name, val);
}

function createDefaultConfig(param, text, defval) {
	var div = document.createElement('div');
	div.innerHTML = text + ": &nbsp";
	var input = createDefaultInput('30px', param, defval);
	div.appendChild(input);
	div.style.marginLeft = '5px';
	return div;
}

function setupConfiguration() {

	var configuration = document.createElement('div');
	$ui.config = configuration; 

	configuration.style.position='fixed';
	configuration.style.textAlign = 'left';
	configuration.style.background = 'white';
	configuration.style.border = "solid gray 2px";

	var div = document.createElement('div');
	div.style.textAlign = 'center';
	div.style.fontWeight = 'bolder';
	div.style.marginBottom = '10px';
	div.style.borderBottom = 'solid gray 2px';
	div.innerHTML = 'Konfiguracja';
	configuration.appendChild(div);

	div = document.createElement('div');
	div.innerHTML = "poziom trola:&nbsp;";
	var input = createDefaultInput('30px', $troll_level, '-5');
	div.appendChild(input);
	div.style.marginLeft = '5px';

	configuration.appendChild(div);

	div = document.createElement('div');
	div.innerHTML = "poziom super trola:&nbsp;";
	input = createDefaultInput('50px', $supertroll_level, '-10');
	div.appendChild(input);
	div.style.marginLeft = '5px';

	configuration.appendChild(div);

	div = document.createElement('div');
	div.innerHTML = "przed nikiem w odpowiedzi:&nbsp;";
	input = createDefaultInput('50px', $before_nick, '--> ');
	div.appendChild(input);
	div.style.marginLeft = '5px';

	configuration.appendChild(div);

	div = document.createElement('div');
	div.innerHTML = "znak cytowania:&nbsp;";
	input = createDefaultInput('50px', $quote_char, '>');
	input.maxLength = '1';
	div.appendChild(input);
	div.style.marginLeft = '5px';

	configuration.appendChild(div);


	div = document.createElement('div');
	div.innerHTML = "po cytowanym tekście:&nbsp;";
	input = createDefaultInput('50px', $after_quoted_text, '-- ');
	div.appendChild(input);
	div.style.marginLeft = '5px';

	configuration.appendChild(div);

	div = document.createElement('div');
	div.innerHTML = "co ile sekund odświeżać listę komentarzy? ";
	var seconds = createDefaultInput('50px', $reload_comments, '30');
	addEvent(seconds, 'change', function(e) {
		var i = parseInt(seconds.value);
		if(isNaN(i)) return;
		if(i>0 && i < 30) seconds.value = 30;
	});
	div.appendChild(seconds);
	div.style.marginLeft = '5px';
	configuration.appendChild(div);

	div = document.createElement('div');
	div.innerHTML = "co ile sekund odświeżać subskrybcje? ";
	var tseconds = createDefaultInput('50px', $reload_tracked_comments, '300');
	addEvent(tseconds, 'change', function(e) {
		var i = parseInt(tseconds.value);
		if(isNaN(i)) return;
		if(i>0 && i < 60) tseconds.value = 60;
	});
	div.appendChild(tseconds);
	div.style.marginLeft = '5px';

	configuration.appendChild(div);

	div = document.createElement('div');
	div.innerHTML = "co ile sekund sprawdzać SG? ";
	var gseconds = createDefaultInput('50px', $reload_sg_data, '300');
	addEvent(gseconds, 'change', function(e) {
		var i = parseInt(gseconds.value);
		if(isNaN(i)) return;
		if(i>0 && i < 300) gseconds.value = 300;
	});
	div.appendChild(gseconds);
	div.style.marginLeft = '5px';

	configuration.appendChild(div);


	div = document.createElement('div');
	div.innerHTML = "ile wyświetlać znaków tytułu subskrypcji?";
	input = createDefaultInput('50px', $subscripction_title_length, '30');
	div.appendChild(input);
	div.style.marginLeft = '5px';

	configuration.appendChild(div);

	div = document.createElement('div');
	div.innerHTML = "ile wyświetlać znaków pierwszego tytułu z SG?";
	input = createDefaultInput('50px', $sg_first_title_length, '30');
	div.appendChild(input);
	div.style.marginLeft = '5px';

	configuration.appendChild(div);


	div = document.createElement('div');
	div.innerHTML = "klikalne linki w komentarzach? ";
	input = createDefaultInput('50px', $do_urlize_comments, 'tak');
	div.appendChild(input);
	div.style.marginLeft = '5px';

	configuration.appendChild(div);

	configuration.appendChild(document.createElement('hr'));

	div = document.createElement('div');
	div.innerHTML = "Poniżej można skonfigurować skróty klawiszowe. działają z przytrzymaniem klawisza Alt";
	configuration.appendChild(div);
	div.style.marginBottom = '10px';
	div.style.marginTop = '10px';

	configuration.appendChild(createDefaultConfig($key_refresh_comments,'odświeżenie komentarzy','f'));
	configuration.appendChild(createDefaultConfig($key_refresh_subscriptions ,'odświeżenie subskrybcji','d'));
	configuration.appendChild(createDefaultConfig($key_refresh_sginfo ,'odświeżenie info SG','s'));
	configuration.appendChild(createDefaultConfig($key_toggle_subscriptions ,'toggle subskrybcji','c'));
	configuration.appendChild(createDefaultConfig($key_toggle_ui ,'toggle ui','v'));
	configuration.appendChild(createDefaultConfig($key_scroll_top ,'na górę strony','q'));
	configuration.appendChild(createDefaultConfig($key_scroll_bottom ,'na dół strony','a'));


	configuration.appendChild(document.createElement('hr'));

	div = document.createElement('div');
	div.innerHTML = "Poniżej można skonfigurować w jaki sposób otwierać linki z subskrybcji, tryb ID otwiera każdy link we własnym, zawesze tym samym oknie (jednak jeśli to okno jest już otwarte w zakładce to trzeba potem na tą zakładę przejść. tryb _blank otwiera zawsze w nowym oknie, tryb _top otwiera zawsze w bierzącym oknie";

	configuration.appendChild(div);
	div.style.marginBottom = '10px';
	div.style.marginTop = '10px';

	configuration.appendChild(createDefaultConfig($how_to_open_window, 'Sposób otwierania subskrybcji','_top'));

	div = document.createElement('div');
	div.style.textAlign = 'right';
	div.style.cssFloat = 'right';
	div.style.margin = '2px';
	
	var span = document.createElement('span');
	span.innerHTML = "<br>" + "ver. " + $ver + "<br>";
	div.appendChild(span);

	var a = document.createElement('a');
	a.href = "http://greasemonkey.salon24.pl/";
	a.innerHTML = a.href;
	div.appendChild(a);
	configuration.appendChild(div);


	var btn = document.createElement('button');
	btn.innerHTML = 'ok';
	btn.style.marginLeft = '5px';
	btn.style.marginBottom = '5px';
	addEvent(btn, 'click', function(e) {configuration.style.display='none'; hideGlass();});

	configuration.appendChild(document.createElement('br'));
	configuration.appendChild(btn);
	configuration.style.display = 'none';

	document.getElementsByTagName('body')[0].appendChild(configuration);
}

function showConfig() {
	showGlass();
	showAsWindow($ui.config);
}

function showAsWindow(win) {
	win.style.zIndex = '300';
	win.style.display = 'block';	
	win.style.position = 'fixed';
	win.style.left = window.innerWidth/2 - win.offsetWidth/2;
	win.style.top = window.innerHeight/2 - win.offsetHeight/2;
}

function saveCommentLoop() {
	if(! $current_comment) return;
	saveComment($current_comment.value);
	setTimeout(saveCommentLoop, 5000);
}

function isWrapPoint(c) {
	return c==' '||c=='\t';
}

function getPrefix(txt, prefix) {
	var r = new RegExp('^['+prefix+']* ?');
	var ret = txt.match(r);
	return ret;
};

function addSpaceAfterQuote(txt, prefix) {
	var r = new RegExp('^(['+prefix+']+)[\\s*]?');
	return txt.replace(r, "$1 ");
}

function getQuotedText(text, prefix) {
	var lines = text.split('\n');
	var res =[];
	for(var i=0;i<lines.length;i++) {
		var tmp = addSpaceAfterQuote(prefix + lines[i], prefix);
		if(tmp.length > 72 && tmp.slice(0,72).lastIndexOf(' ') != -1) {
			var wp = tmp.slice(0,72).lastIndexOf(' ');
			res[res.length] = tmp.slice(0,wp);
			res[res.length] = getPrefix(tmp,prefix) + tmp.slice(wp+1, tmp.length);
		}
		else res[res.length] = tmp;
	}
	return res.join('\n');
}

function appendReplyForm(cmt) {
	if($current_response && $current_response.parentNode) {
		$current_response.parentNode.removeChild($current_response);
	}

	var btn = document.createElement('button');
	var commentlink = $state.reply_url

	var response = document.createElement('div');

	var div = document.createElement('div');
	div.style.position = 'relative';
	div.style.width = '300px';
	div.style.height = '300px';

	var text = simpleDecode(cmt.body.innerHTML);

	var aqt = getParam($after_quoted_text, '-- ');
	var qc = getParam($quote_char, '>').slice(0,1);
	if(qc)
		text = getQuotedText(text, qc);
	
	text = getParam($before_nick, '--> ') + cmt.nick +'\n' + text + '\n' + aqt + '\n';

	var ta = document.createElement('textarea');
	ta.value = text;
	ta.style.width = '460px';
	ta.style.height = '290px';
	ta.style.left = '0px';
	ta.style.right = '0px';
	ta.style.top = '20px';
	ta.style.position = 'absolute';
	ta.name = 'cbody';

	div.appendChild(ta);

	
	var draft = getCommentDraft();
	if(draft && draft != "") {
		showDraftCommentWindow("wygląda na to że masz niewysłany komentarz", draft, cmt.htmlElement, 
		function() {
			ta.value = draft;
			saveComment("");
		},
		function() {
			saveComment("");
		});
	}

	var handleRight = document.createElement('div');
	handleRight.style.width = '5px';
	handleRight.style.height = '295px';
	handleRight.style.backgroundColor = 'Gray';
	handleRight.style.position = 'absolute';
	handleRight.style.left = '465px';
	handleRight.style.top = '20px';
	handleRight.style.cursor = 'e-resize';

	div.appendChild(handleRight);

	var handleBottom = document.createElement('div');
	handleBottom.style.width = '465px';
	handleBottom.style.height = '5px';
	handleBottom.style.backgroundColor = 'Gray';
	handleBottom.style.position = 'absolute';
	handleBottom.style.top = '315px';
	handleBottom.style.cursor = 's-resize';

	div.appendChild(handleBottom);

	var handleCorner = document.createElement('div');
	handleCorner.style.width = '5px';
	handleCorner.style.height = '5px';
	handleCorner.style.backgroundColor = 'Gray';
	handleCorner.style.position = 'absolute';
	handleCorner.style.top = '315px';
	handleCorner.style.left = '465px';
	handleCorner.style.cursor = 'se-resize';

	div.appendChild(handleCorner);

	new dragObject(handleRight, null, new Position(305, 20), new Position(460, 20), null, function(newPos, element) {
			var x = newPos.X;
			div.style.width =  (x + 5) + 'px';

			if(element != handleCorner)
			handleCorner.style.left = x + 'px';

			if(element != handleRight)
			handleRight.style.left = x + 'px';

			handleBottom.style.width = x + 'px';

			ta.style.width = (x - 5) + 'px';
			}, 
	null, false);

	new dragObject(handleBottom, null, new Position(0, 15), new Position(0, 800), null, function(newPos, element) {
			var y = newPos.Y;	
			div.style.height = (y + 5) + 'px';
			if(element != handleCorner)
			handleCorner.style.top = y + 'px';
			handleRight.style.height = (y - 20) + 'px';

			if(element != handleBottom)
			handleBottom.style.top = y + 'px';

			ta.style.height = (y - 25) + 'px';
			},
	null, false);

	new dragObject(handleCorner, null, new Position(305, 20), new Position(460, 800), null, function(newPos, element) {
			var y = newPos.Y;	
			div.style.height = (y + 5) + 'px';
			if(element != handleCorner)
			handleCorner.style.top = y + 'px';
			handleRight.style.height = (y - 20) + 'px';

			if(element != handleBottom)
			handleBottom.style.top = y + 'px';

			ta.style.height = (y - 25) + 'px';

			var x = newPos.X;
			div.style.width =  (x + 5) + 'px';

			if(element != handleCorner)
			handleCorner.style.left = x + 'px';

			if(element != handleRight)
			handleRight.style.left = x + 'px';

			handleBottom.style.width = x + 'px';

			ta.style.width = (x - 5) + 'px';

		},
	null, false);

	response.appendChild(div);

	btn.innerHTML= 'wyślij';
	btn.style.position = 'relative';
	btn.style.top = '20px';
	addEvent(btn, 'click', function(e) {
		postComment(ta, commentlink); 
		response.parentNode.removeChild(response); 
		$current_comment= undefined; 
		e.preventDefault()
	});
	response.appendChild(btn);

	btn = document.createElement('button');
	btn.style.position = 'relative';
	btn.style.top = '20px';
	btn.innerHTML = 'anuluj';
	addEvent(btn, 'click', function(e) {
		response.parentNode.removeChild(response); 
		$current_comment = undefined; 
		saveComment("");
	});
	response.appendChild(btn);

	$current_response = response;
	$current_comment = ta;

	cmt.htmlElement.appendChild(response);
	ta.focus();
	ta.select();

	setTimeout(saveCommentLoop, 5000);

}

function postComment(textarea, commentlink) {
	blogid = commentlink.split('/')[3].split(',')[0];
	var text = textarea.value.replace(/^\s+|\s+$/g, '');
	if(text.length <= 0) {
		alert('pusty komentarz? bezsensu.');
		return;
	}

	text = textarea.value.split('\n');

	var title=text[0];
	var first_notempty = 1;
	delete text[0];

	//remove empty lines from top of the text;
	for(var i=1;i<text.length;i++) {
		if(text[i].length != 0) {
			first_notempty = i;
			break;
		}
	}
	text = text.splice(first_notempty, text.length);

	var cbody=text.join('\n');
	var postData = ''

	postData += 'blog_id='+encodeURIComponent(blogid);
	postData += '&ctitle='+encodeURIComponent(fixSymbols(title));
	postData += '&cbody='+encodeURIComponent(fixSymbols(cbody))+" ";
	postData += '&submit=Wyślij';
	postData = fixEncoding(postData);

	
	var url = document.location.href.replace(/\/[^/]*$/, '') +'/'+blogid +',comment_save.html';
	var host = document.location.href.split('/')[2];
	//GM_log(url);
	//GM_log(postData);
	//GM_log(host);

	var cookie = document.cookie
		if(cookie.split(' ').length>1) {
			var ccheck = cookie.split(' ')[0];
			cookie = cookie.split(' ')[1];
			ccheck.replace(/;$/,'');
		}

	// submit comment

	GM_xmlhttpRequest({
		method: 'POST',
		overrideMimeType : 'text/html; charset=iso-8859-2',
		url: url,
		headers: {
			'Cookie': document.cookie,
			'Accept-Charset': 'ISO-8859-2',
			'Content-Type':'application/x-www-form-urlencoded',
			'Content-Length': postData.length
		},
		data: postData,
		onload: function(responseDetails) {
			//GM_log('status:\n' + responseDetails.status);
			//GM_log('statustext:\n'+responseDetails.statusText);
			//GM_log('responsetext:\n'+responseDetails.responseText);
			saveComment("");
			refreshComments();
		},
		onerror: function(responseDetails) {
			GM_log('ERROR!');
			GM_log('status:\n' + responseDetails.status);
			GM_log('statustext:\n'+responseDetails.statusText)
			GM_log('responsetext:\n'+responseDetails.responseText)
		 }
	});
}

function setupComment(cmt, urlize) {
	// set id's to use in future
	cmt.body.id='body'+$X+cmt.htmlElement.id
	cmt.title.id='title'+$X+cmt.htmlElement.id
	cmt.cc.id = 'cc'+$X+cmt.htmlElement.id

	if(urlize) urlizeComment(cmt.body);


	// show mouse pointer on comments count to show/hide comments
	//
	cmt.cc.style.cursor='pointer';

	// change comment link
	//

	var link = $state.reply_url.replace(/comment_add/,'index') + '#comment_' + cmt.number;
	var el = document.createElement('a');
	el.innerHTML = 'link do komentarza';
	el.style.textDecoration = 'underline';
	el.href = link;

	cmt.link.parentNode.replaceChild(el, cmt.link);
	cmt.link = el;
	addEvent(cmt.link, 'click', function(e) {$trueWindow.top.ShowLink(link); return false;});

	// add reply link
	//
	el = document.createElement('a');
	el.innerHTML = 'odpowiedz'
	el.style.textDecoration = 'underline';
	el.href = '#';
	el.id='reply'+$X+cmt.htmlElement.id
	cmt.reply = el;
	addEvent(el, 'click', function(e) {appendReplyForm(ecomment(e))});


	cmt.link.parentNode.insertBefore(el, cmt.link);


	//add comment link

	el = document.createElement('a');
	el.innerHTML = 'skomentuj'
	el.style.textDecoration = 'underline';
	el.href = $state.reply_url
	el.id='comment'+$X+cmt.htmlElement.id
	cmt.reply = el;

	cmt.link.parentNode.insertBefore(el, cmt.link);

	// add ignore link
	//
	el = document.createElement('a');
	el.style.textDecoration = 'underline';
	el.href = '#'
	el.id='blacklist'+$X+cmt.htmlElement.id
	cmt.blacklist = el;

	cmt.link.parentNode.insertBefore(el, cmt.link);

	// add vote for author
	//
	var span = document.createElement('span');

	el = document.createElement('img');
	el.src = $media.plusicon;
	el.style.marginLeft = '5px';
	span.appendChild(el);
	cmt.votepro = el;
	addEvent(el, 'click', function(e) {voteForAuthor(enick(e), true);});
	el.id='votepro'+$X+cmt.htmlElement.id;

	el = document.createElement('img');
	el.src = $media.minusicon;
	el.style.marginLeft = '2px';
	el.style.marginRight = '5px';
	span.appendChild(el);
	cmt.voteagainst = el;
	addEvent(el, 'click', function(e) {voteForAuthor(enick(e), false);});
	el.id='voteagainst'+$X+cmt.htmlElement.id;

	el = document.createElement('div');
	el.style.color = 'gray';
	el.style.display = 'inline';
	el.innerHTML = getVotes(cmt.nick)
	cmt.votecount = el;

	cmt.cc.parentNode.insertBefore(span, cmt.cc.nextSibling);
	span.appendChild(el);

	addEvent(cmt.blacklist, 'click', function(e) {toggleBlacklisted(enick(e));});

	addEvent(cmt.cc, 'click', function(e){
			toggleDisplay(cmt);
	});


	el = document.createElement('li');
	cmt.superTrollElement = el;
	el.innerHTML = "<i>"+cmt.nick+"</i> jest smutnym supertrolem";
	el.style.color='gray';
	el.style.background='#f3f3f3';
	el.style.cursor = 'pointer';
	el.className = 'comment';
	addEvent(el, 'click', function(e) {toggleDisplay(cmt);}); 


	displayComment(cmt);
}

function displayComment(cmt) {
	isBlacklisted(cmt.nick) ? displayBlacklisted(cmt) : displayNormal(cmt);
	cmt.votecount.innerHTML = getVotes(cmt.nick)
}

function setupNoteViewPage() {
	var cmt_write = getElementByClass('post_comment_write');
	$state.reply_url = cmt_write.getElementsByTagName('a')[0].href; // save reply link
	$state.post_id = $state.reply_url.split('/')[3].split(',')[0]; // save note id

	// make post title link directly to this post.
	var a = document.createElement('a');
	var title = getElementByClass('post_title');
	var el = document.getElementById("section_header_blog_title").getElementsByTagName('a')[0];

	$state.post_url = el.href.replace(/index.html/,$state.post_id + ",index.html"); // save post url
	if(el.href.match('/index.html')) a.href = $state.post_url;

	a.style.textDecoration = 'none';
	a.innerHTML = title.innerHTML;

	$state.post_title = title.innerHTML; // save post title element

	a.id = 'post_title_link';
	title.innerHTML = "";
	title.appendChild(a);

	gatherComments();
	applyToAllComments(setupComment);

	setTimeout(doReloadComments, 60 * 1000);
	setTimeout(doCheckSG, 60 * 1000);

}

function clearLoginInfo() {
	$store.set($store.login, 0);
}

function setupLoginPage() {
	clearLoginInfo();
}

function setupMainPage() {
	doRememberSG();
}

function setupNoteEditPage() {
	setupMCE();
}

function setup() {

	$loginInfo.login = GM_getValue($store.login);

	if (getElementByClass('post_comment_write')) setupNoteViewPage();

	if(typeof($trueWindow.tinyMCE)!="undefined") setupNoteEditPage();

	if(window.location.href == 'http://www.salon24.pl/index.html') setupMainPage();

	for(var i=0;i<document.forms.length;i++) {
		if(document.forms[i].action.match(/\/auth.html/)) {
			setupLoginPage();
			break;
		}
	}

	init_ui();

	setupConfiguration();

	setTimeout(doReloadSubscriptions, 60 * 1000);
	setTimeout(doCheckSG, getParam($reload_sg_data, '200') * 1000);

	update_ui();
	showCurrentSubscriptions();
}

function doReloadComments() {
	var secs = parseInt(getParam($reload_comments, 100));
	if(secs == 0 || isNaN(secs) || secs < 0) {
		setTimeout(doReloadComments, 60 * 1000); //check again in 1 minute
		return;
	}

	if($window_active) {
		refreshComments();
		getLoginInfo();
	}

	if(secs<30) secs = 30; //
	setTimeout(doReloadComments, secs * 1000);
}

function doCheckSG() {
	var secs = parseInt(getParam($reload_sg_data, 300));
	if(secs == 0 || isNaN(secs) || secs < 0) {
		setTimeout(doCheckSG, 60 * 1000); //check again in 1 minute
		return;
	}

	if($window_active) {
		checkSG();
	}

	if(secs<300) secs = 300; //
	setTimeout(doCheckSG, secs * 1000);
}

function doReloadSubscriptions() {
	var secs = parseInt(getParam($reload_tracked_comments, 100));
	if(secs == 0 || isNaN(secs) || secs < 0) {
		setTimeout(doReloadSubscriptions, 60 * 1000); //check again in 1 minute
		return;
	}

	if($window_active) {
		checkTrackedComments();
	}

	if(secs<60) secs = 60; //
	setTimeout(doReloadSubscriptions, secs * 1000);
}

function toggleMCE(e, link) {
	var instance = $trueWindow.top.tinyMCE.getInstanceById('blog_body');
	if(instance) {
		link.innerHTML = 'przywróć pożeracza'
			$trueWindow.tinyMCE.execCommand('mceRemoveControl', false, 'blog_body');
	}
	else {
		link.innerHTML = 'zniknij pożeracza'
			$trueWindow.tinyMCE.execCommand('mceAddControl', false, 'blog_body');
	}
	cancelEvent(e);
}

function yt_cleanup_wrapper(inst,type,content) {
	if(type=="insert_to_editor") {
		//substitute the YT <object> to [yt:url] macro
		content = mceOnInsertToEditor(content);	
	}
	if(type=="get_from_editor") {
		//substitute the [yt:url] macro with YT <object> on "Submit"
		content = mceOnGetFromEditor(content);	
	}
	if(type=="submit_content") {
		setTimeout(function() {savePost("");}, 10);
	}

	content = $trueWindow.tinyMCE.orig_customCleanup(inst,type,content);

	return content;
}

function mceOnInsertToEditor(html) {
	var tmp = document.createElement('div');
	tmp.innerHTML = html;
	var objects = tmp.getElementsByTagName('object');
	for(var i=0;i<objects.length;i++) {
		var o = objects[i];
		var s = document.createElement('span'); // number of divs will grow, fix later.
		s.innerHTML = getMacro(o);
		o.parentNode.insertBefore(s, o); //for some secret and evil reason replaceChild works only on first object...
	}

	return tmp.innerHTML;
}

function getMacro(obj) {
	var embed = obj.getElementsByTagName('embed')[0];
	if(!embed) return "";
	return "[yt:"+embed.src.replace(/\/v\//,"/watch?v=").replace(/&.*$/,"") +"]";
}

function mceOnGetFromEditor(text) {
	// youtube
	text = text.replace(/\[yt:http:\/\/[^?]*\?v=([^\&\]]*)[^\]]*\]/g,'<object width="425" height="344"><param name="movie" value="http://youtube.com/v/$1&hl=en&fs=1"></param><param name="allowFullScreen" value="true"></param><embed src="http://www.youtube.com/v/$1&hl=en&fs=1" type="application/x-shockwave-flash" allowfullscreen="true" width="425" height="344"></embed></object>');
	// &%$@*#@@#$!!@$#
	text = text.replace(/script/,"&#115;cript");
	return text;
}

function replaceUrl(url) {
	return url.replace(/http:\/\/[^?]*\?v=([^\&\]]*)[^\]]*/g,'<object width="425" height="344"><param name="movie" value="http://youtube.com/v/$1&hl=en&fs=1"></param><param name="allowFullScreen" value="true"></param><embed src="http://www.youtube.com/v/$1&hl=en&fs=1" type="application/x-shockwave-flash" allowfullscreen="true" width="425" height="344"></embed></object>');
}

function savePostLoop() {
	if(!$trueWindow.tinyMCE) return;
	savePost($trueWindow.tinyMCE.selectedInstance.getBody().innerHTML);
	setTimeout(savePostLoop, 5000);
}

function setupMCE() {
	if(typeof($trueWindow.tinyMCE)=="undefined") return;

	var ta = document.getElementsByTagName('textarea')[0];
	var toggle = document.createElement('a');
	toggle.href = '#';
	toggle.innerHTML = "zniknij pożeracza";
	addEvent(toggle, 'click', function(e) {toggleMCE(e, toggle)});
	ta.parentNode.parentNode.insertBefore(toggle, ta.parentNode.nextSibling);

	//wrap MCE cleanup with ours
	$trueWindow.tinyMCE.orig_customCleanup=$trueWindow.tinyMCE._customCleanup;
	$trueWindow.tinyMCE._customCleanup = yt_cleanup_wrapper;

	//remove YT <object> and replace it with [yt:url] macro
	html= replaceHtml($trueWindow.tinyMCE.selectedInstance.getBody().innerHTML);
	
	$trueWindow.tinyMCE._setHTML($trueWindow.tinyMCE.selectedInstance.getDoc(), html);

	setTimeout(savePostLoop, 5000);

	var el = document.createElement('img');
	el.src = "data:image/gif,GIF89a%14%00%14%00%C3%09%00%02(Jn%8A%A2%C9%CF%D9Vjz%ED%EE%F1%AE%B7%C3%15%5C%7F%DD%DF%E4%82%8F%9D%FD%FD%FD%078Z%9D%A8%B0%B7%C3%D2j%7D%8E%8A%9B%AF%00%00%00!%F9%04%01%00%00%0F%00%2C%00%00%00%00%14%00%14%00%00%04%9E%F0%C9I%AB%BD8%3F%B2%DA%18%CDBh%84%E04NQ%9C%8E0Z%04%D3%14%C2a%0BE%C7%BC%94%D0%D4%84%A0%00%000%C8%04%15B%EB%40H%24%08%0A%85%C1p0%F1%1E%85%06%D3%99pH%03%B6%C3%8C%82%00r%8B%06%9A%8D%81%A0%FC%0E%5C%06%20%AA%20%DC%1A%EE%DA%99%5E%BF%93%055Us%0DNa%02m%134%80CQ%05va*%14%07-%0Ds%0A%84%81U%0E%07%15%0C%1D%0A%00%0D%25a%04%0D%0C%16%079.%0F%A4%A5%05%9C%A8%0C%9BMO%93%0C%B0%188%0E%08%08)H%1A%C0%C1%C1%11%00%3B";
	var a = document.createElement('a');
	a.className = 'mceButtonNormal';
	a.appendChild(el);
	var tmp = document.getElementById('mce_editor_0_charmap');
	tmp.parentNode.insertBefore(a, tmp);
	addEvent(el, 'click', showYouTubeWindow);

	var title = getElementByClass('page_title');
	
	var draftPost = getPostDraft();
	if(draftPost && draftPost != "" && draftPost != "<br>") {
		showDraftNoteWindow("wygląda na to że masz niewysłaną notkę", draftPost, title, 
		function() {
			savePost("");
			$trueWindow.tinyMCE.execCommand('mceInsertContent', false, draftPost);
		},
		function() {
			savePost("");
		});
	}
};

function urlizeComments() {
	var cmts = getElementsByClass('comment_body');
	if(!cmts) return;
	if(getParam($do_urlize_comments, "nie") != "tak") return;
	for(var i=0;i<cmts.length;i++) {
		var cmt = cmts[i];
		urlizeComment(cmt);
	}
}

function urlizeComment(cmt) {
	cmt.innerHTML = cmt.innerHTML.replace(/(ftp|http|https|file):\/\/(\#|\~|\.|\$|\-|\_|\+|\!|\*|\(|\)|\,|\i|\@|\:|\;|\/|\?|\&|\%|\=|\w)+(\b|$)/gim, '<a href="$&" class="my_link" target="_blank">$&</a>').replace(/([^\/])(www[\S]+(\b|$))/gim,'$1<a href="http://$2" class="my_link" target="_blank">$2</a>');
}

function isIframe() {
	return top.location.href != document.location.href;
}

function showDraftNoteWindow(title, draft, elem, funcOk, funcCancel) {
	var width = 430;
	var height = 400;
	var pos = findPos(elem);

	var win = document.createElement('div');
	win.style.position = 'absolute';
	win.style.width = width;
	win.style.height = height;
	win.style.background = 'white';
	win.style.border = 'solid black 1px';
	win.style.textAlign = 'left';
	win.style.zIndex = '200';
	win.style.display = 'block';

	//GM_log(window.innerHeight);

	var el = document.createElement('div');
	el.innerHTML = title;
	el.style.width = width;
	el.style.background = 'black';
	el.style.color = 'white';
	el.style.fontWeight = 'bolder';
	win.appendChild(el);


	var preview = document.createElement('div');
	preview.style.border = 'solid black 1px';
	preview.style.height = '350px';
	preview.style.width = '428px';
	preview.style.background = '#f3f3f3';
	preview.style.overflow = 'auto';
	preview.innerHTML = draft;

	win.appendChild(preview);

	var ok = document.createElement('button');
	ok.style.display = 'inline';
	ok.innerHTML = 'wkej';


	var cancel = document.createElement('button');
	cancel.style.display = 'inline';
	cancel.innerHTML = 'nieee chcem - skasuj!';
	addEvent(cancel, 'click', function(e) {
		if(funcCancel) funcCancel();
		win.parentNode.removeChild(win);
		hideGlass();
		savePost("");
	});


	addEvent(ok, 'click', function() {
		if(funcOk) funcOk();
		win.parentNode.removeChild(win);
		hideGlass();
	});

	win.appendChild(ok);
	win.appendChild(cancel);

	document.body.appendChild(win);
	showGlass();
	showAsWindow(win);
}


function showDraftCommentWindow(title, draft, elem, funcOk, funcCancel) {
	var width = 430;
	var height = 400;
	var pos = findPos(elem);

	var win = document.createElement('div');
	win.style.position = 'absolute';
	win.style.width = width;
	win.style.height = height;
	win.style.background = 'white';
	win.style.border = 'solid black 1px';
	win.style.zIndex = '200';
	win.style.display = 'block';

	//GM_log(window.innerHeight);

	var el = document.createElement('div');
	el.innerHTML = title;
	el.style.width = width;
	el.style.background = 'black';
	el.style.color = 'white';
	el.style.fontWeight = 'bolder';
	win.appendChild(el);


	var preview = document.createElement('div');
	var ta = document.createElement('textarea');
	ta.style.height = '350px';
	ta.style.width = '428px';
	ta.style.border = 'none';
	ta.style.background = '#f3f3f3';
	ta.disabled = true;
	ta.innerHTML = draft;

	preview.appendChild(ta);

	win.appendChild(preview);

	var ok = document.createElement('button');
	ok.style.display = 'inline';
	ok.innerHTML = 'wkej';


	var cancel = document.createElement('button');
	cancel.style.display = 'inline';
	cancel.innerHTML = 'nieee chcem - skasuj!';
	addEvent(cancel, 'click', function(e) {
		if(funcCancel) funcCancel();
		saveComment("");
		win.parentNode.removeChild(win);
		hideGlass();
	});


	addEvent(ok, 'click', function() {
		if(funcOk) funcOk();
		win.parentNode.removeChild(win);
		hideGlass();
	});

	win.appendChild(ok);
	win.appendChild(cancel);

	document.body.appendChild(win);
	showGlass();
	showAsWindow(win);
}

function showYouTubeWindow() {
	var width = 430;
	var embeddedHeight = 407;
	var startHeight = 85;

	var win = document.createElement('div');
	win.style.position = 'absolute';
	win.style.width = width;
	win.style.height = startHeight;
	win.style.background = 'white';
	win.style.border = 'solid black 1px';
	win.style.zIndex = '200';

	win.style.left = window.innerWidth/2 - 400;
	win.style.top = window.innerHeight/2 - 150;
	//win.style.top = document.documentElement.clientHeight/2 - 450;	

	var el = document.createElement('div');
	el.innerHTML = 'podaj linka do stronki jutuba:';
	el.style.width = width;
	el.style.background = 'black';
	el.style.color = 'gray';
	el.style.fontWeight = 'bolder';
	win.appendChild(el);

	var input = document.createElement('input');
	input.type='text';
	input.style.width=width-2;
	win.appendChild(input);

	var preview = document.createElement('div');
	win.appendChild(preview);

	var ok = document.createElement('button');
	ok.style.display = 'inline';
	ok.innerHTML = 'pokaż!';

	var cancel = document.createElement('button');
	cancel.style.display = 'inline';
	cancel.innerHTML = 'nieee chcem!';
	addEvent(cancel, 'click', function(e) {
		win.parentNode.removeChild(win);
		hideGlass();
	});

	var valid = false;
	addEvent(ok, 'click', function() {
		if(!valid) {
			var res = replaceUrl(input.value);
			if(res.match("^<object")) {
				preview.innerHTML = res;
				win.style.height = embeddedHeight;
				ok.innerHTML = 'wklejam!';
				input.disabled = 'true';
				valid = true;
			} else {
				preview.innerHTML = 'coś słaba ta linka...';
			}
		} else {
			$trueWindow.tinyMCE.execCommand('mceInsertContent', false, '[yt:'+input.value+']');
			win.parentNode.removeChild(win);
			hideGlass();
		}
	});

	win.appendChild(ok);
	win.appendChild(cancel);

	document.body.appendChild(win);
	showGlass();

	win.style.zIndex = '300';
	win.style.display = 'block';	
	win.style.position = 'fixed';
	win.style.left = window.innerWidth/2 - win.offsetWidth/2;
	win.style.top = window.innerHeight/2 - win.offsetHeight/2 - 200;
}

function updateMyNote() {
	var list = getElementByClass('comments_list');
	if(!list) {
		$store.setPrivate($store.my_last_post_cmts, 0);
	} else {
		$store.setPrivate($store.my_last_post_cmts, list.getElementsByTagName('li').length);
	}
	$store.setPrivate($store.my_last_unread_cmts, 0);
}

function updateOtherNote() {
	var tmp = isBeingTracked($state.post_id);
	if(tmp) {
		if($comments.htmlList) setTrackedCount($state.post_id, $comments.htmlList.getElementsByTagName('li').length);
		else setTrackedCount($state.post_id, 0);

		setLastTrackedCount($state.post_id, 0);
	}
}

function rememberCommentsOnThisPage() {
	if($state.post_id && $state.post_id == $loginInfo.my_last_post_id) {
		updateMyNote();
	} else if ($state.post_id && $state.post_id != $loginInfo.my_last_post_id) {
		updateOtherNote();
	}
}

function onWindowVisible() {
	if($state.post_id && $state.post_id == $loginInfo.my_last_post_id) {
		refreshComments();
	}
	showCurrentSubscriptions();
	update_ui();
}

function onWindowFocus(e) {
	if($window_active) return;
	onWindowVisible();
	$window_active = true;
}

function onWindowBlur(e) {
	$window_active = false;
	$mousemoved = false;
	rememberCommentsOnThisPage();
}

function showLoadingInfo() {
	$state.comments_updating=1;
	$ui.small.himg.src = $media.throbbericon;
	$ui.full.himg.src = $media.throbbericon;
	update_ui();
}


function isLoggedIn() {
	var el = getElementByClass('myblog');
	if(el) return el.className.match(/DisplayNone/) == null;
	
	el = getElementByClass('bdL');
	if(!el) return false;
	var list = getElementsByClass('visNAi');
	for(var i=0;i<list.length;i++) {
		if(list[i].innerHTML == "rejestracja") {
			if(list[i].offsetHeight > 0) return false;
			else return true;
		}
	}
	return true;
}

function getLoginInfo() {
	try {
		loadPage('http://www.salon24.pl/myblog.html', setupLoginInfo);
	} catch(error) {}
}

function setupLoginInfo(responseDetails) {
	var div = parseHtmlResponse(responseDetails.responseText);
	if(!div) return;

	// setup login
	var ret = getElementsByCondition(function(el) {
			if(el.id == "section_header_blog_about") return el;
	}, div)[0];

	if(!ret) return;

	var a = ret.getElementsByTagName('h1')[0].getElementsByTagName('a')[0];
	$loginInfo.login = a.innerHTML;
	$store.set($store.login, $loginInfo.login);

	// setup last comments

	var cmts = getElementByClass('comments_list', div);
	if(cmts) $loginInfo.author_post_replies = cmts.getElementsByTagName('li').length;
	else $loginInfo.author_post_replies = 0;

	var tmp = getElementByClass('post_comment_write', div);
	if(tmp) $loginInfo.my_last_post_id = tmp.getElementsByTagName('a')[0].href.split('/')[3].split(',')[0];
	

	var cmts = $store.getPrivate($store.my_last_post_cmts);
	if(!cmts && cmts != 0) {
		$store.setPrivate($my_last_post_cmts, $loginInfo.author_post_replies);
		$store.setPrivate($store.my_last_unread_cmts, 0);
	}
	else {
		var dif = $loginInfo.author_post_replies - cmts;
		var l = document.createElement('a');
		l.innerHTML = $loginInfo.login + " <b>("+dif +")</b>";
		l.href = 'http://www.salon24.pl/myblog.html';
		$store.setPrivate($store.my_last_unread_cmts, dif);
	}


	update_ui();
	showCurrentSubscriptions();
}

function saveComment(text) {
	if(text=="" || text) {
		$store.set($comment_draft, text);
	}
}

function getCommentDraft() {
	return GM_getValue($comment_draft);
}

function savePost(text) {
	if(text=="" || text) {
		$store.set($post_draft, text);
	}
}

function getPostDraft() {
	return GM_getValue($post_draft);
}

function hideLoadingInfo() {
	$state.comments_updating = 0;
	$ui.small.himg.src = $media.homeicon;
	$ui.full.himg.src = $media.homeicon;
	update_ui();
}

function scrollToTop() {
	window.scroll(0, 0);
}

function scrollToBottom() {
	var postList = getElementByClass('posts_list');
	var pos = findPos(postList);
	window.scroll(0, pos.top - window.innerHeight);
}

function ord(str) {
	return str.charCodeAt(0);
}

$mousemoved = false;
function mousemove() {
	if($mousemoved) return;
	onWindowVisible();
	$mousemoved = true;
}

function keypressed(e) {
	if (e.altKey) {
		switch(e.which) {
			case ord(getParam($key_refresh_comments, 'f')):
				cancelEvent(e);
				refreshComments();
				getLoginInfo();
				break;
			case ord(getParam($key_refresh_subscriptions, 'd')):
				checkTrackedComments();
				break;
			case ord(getParam($key_refresh_sginfo, 's')):
				checkSG();
				break;
			case ord(getParam($key_toggle_subscriptions, 'c')):
				toggleSubscriptions();
				break;
			case ord(getParam($key_toggle_ui, 'v')):
				toggleUI();
				break;
			case ord(getParam($key_scroll_top, 'q')):
				scrollToTop();
				break;
			case ord(getParam($key_scroll_bottom, 'a')):
				scrollToBottom();
				break;
		}
	}
}

function showGlass() {
	if($ui.blocker) $ui.blocker.style.display = 'block';
}

function hideGlass() {
	if($ui.blocker) $ui.blocker.style.display = 'none';
}

function trackThisNote(e) {
	setTrackedUrl($state.post_id, $state.post_url);
	setTrackedTitle($state.post_id, $state.post_title);
	if($comments.htmlList)
		setTrackedCount($state.post_id, $comments.htmlList.getElementsByTagName('li').length);
	else 
		setTrackedCount($state.post_id, 0);
}

function getTrackedUrl(id) {
	return GM_getValue($loginInfo.login + '_track_'+id + '_url');
}

function getTrackedCount(id) {
	return GM_getValue($loginInfo.login + '_track_'+id + '_comments');
}

function getTrackedTitle(id) {
	return GM_getValue($loginInfo.login + '_track_'+id + '_title');
}

function setTrackedTitle(id, title) {
	return $store.set($loginInfo.login + '_track_'+id + '_title', title);
}


function setTrackedUrl(id, url) {
	$store.set($loginInfo.login + '_track_'+id + '_url', url);
	var tmp = GM_getValue($loginInfo.login+ " " +$tracked_link_list);
	if(!tmp) tmp = "";
	tmp = tmp.split($X);

	for(var i=0;i<tmp.length;i++) {
		if(id == tmp[i])	return;
	}

	tmp[tmp.length] = id;
	$store.set($loginInfo.login + " " + $tracked_link_list, tmp.join($X));
}

function setTrackedCount(id, count) {
	$store.set($loginInfo.login + '_track_'+id + '_comments', count);
}


function getLastTrackedCount(id) {
	return GM_getValue($loginInfo.login+'_track_'+id + '_comments_lastcheck');
}

function setLastTrackedCount(id, count) {
	$store.set($loginInfo.login +'_track_'+id + '_comments_lastcheck', count);
}

$tracked_reloading = 0;
function checkTrackedComments() {
	var tracked = document.createElement('div');
	tracked.fontSize = 'smaller';
	tracked.paddingLeft = '13px';
	$state.tracked_new_replies_total = 0;
	var tmp = GM_getValue($loginInfo.login + " " +$tracked_link_list);
	if(!tmp) return;

	tmp = tmp.split($X);
	$tracked_reloading = tmp.length - 1;
	$ui.full.watch_icon.src = $media.throbbericon;
	$ui.small.wimg.src = $media.throbbericon;

	for(var i=0;i<tmp.length;i++) {
		if(tmp[i]=="") continue;
		checkTrackedNoteComments(tmp[i], tracked);
	}
}

function showCurrentSubscriptions() {
	if(!$store.getPrivate($store.tracked_new_replies_total)) $store.setPrivate($store.tracked_new_replies_total, 0);

	var login = GM_getValue($store.login);
	var tracked = document.createElement('div');
	var tmp = GM_getValue(login + " " +$tracked_link_list);
	if(!login && isLoggedIn()) return;
	if(!tmp) {
		var d = document.createElement('div');
		removeChildren($ui.full.tracked_list_win);
		$ui.full.tracked_list_win.appendChild(d);
		$state.tracked_new_replies_total = 0;
		return;
	}

	tmp = tmp.split($X);

	$state.tracked_new_replies_total = 0;
	for(var i=0;i<tmp.length;i++) {
		var id = tmp[i];
		if(id=="") continue;
		var c = getLastTrackedCount(id);
		if(!c) {
			c = getTrackedCount(id);
			if(c) setLastTrackedCount(id, c);
		}
		updateTrackedLink(id, c, tracked);
		$state.tracked_new_replies_total += c - getTrackedCount(id);
	}

	$store.setPrivate($store.tracked_new_replies_total, $state.tracked_new_replies_total);

	tracked.fontSize = 'smaller';
	tracked.paddingLeft = '13px';
	$ui.full.tracked_list = tracked;
	$ui.full.tracked_list_win.replaceChild(tracked, $ui.full.tracked_list_win.firstChild);
}

function updateTrackedLink(id, currentCount, div) {
	var t = getTrackedTitle(id);
	var url = getTrackedUrl(id);
	var c = currentCount - getTrackedCount(id);
	setLastTrackedCount(id, currentCount);
	var len = getParam($subscripction_title_length, 30);
	if(t.length > len) t = t.slice(0, len) + '...';
	var a = document.createElement('a');
	a.innerHTML = "<b>("+c+")</b>&nbsp;" + t;
	a.href = url;
	a.target = id;
	a.className = '.glink';
	a.style.textDecoration = 'none';
	a.style.display = 'block';
	a.title = '[przejdź do notki, ctrl+click: odsubskrybuj]';
	div.appendChild(a);
	addEvent(a, 'click', function(e) {
			onTrackedLinkClicked(e, a, id, currentCount);
	});
}

function onTrackedLinkClicked(e, a, id, cnt) {
	cancelEvent(e);
	if(e.ctrlKey) {
		stopTracking(id,"Przestać śledzić komentarze pod" +a.href + " ?");
		showCurrentSubscriptions();
		update_ui();
	} else {
		var mode = getParam($how_to_open_window);
		if(mode == "ID")
			var w = window.open(a.href, id);
		else
			var w = window.open(a.href, mode);
	}
}

function stopTracking(id, msg) {
	var msg = msg || "Przestać śledzić komentarze?";
	var test = confirm(msg);
	if(test) {
		var tmp = GM_getValue($loginInfo.login + " " + $tracked_link_list);
		if(!tmp) return;

		tmp = tmp.split($X);
		var ret = [];

		for(var i=0;i<tmp.length;i++) {
			if(tmp[i]!=id)	ret[ret.length] = tmp[i];
		}
		$store.set($loginInfo.login + " " + $tracked_link_list, ret.join($X));
	}
}

function isBeingTracked(id) {
	var tmp = GM_getValue($loginInfo.login+ " " + $tracked_link_list);
	if(!tmp) return;

	tmp = tmp.split($X);
	var ret = [];

	for(var i=0;i<tmp.length;i++) {
		if(tmp[i]==id) return true;
	}
	return false;
}


function checkTrackedNoteComments(id, tracked) {
	var url = getTrackedUrl(id);
	try {
		loadPage(url, onload=function(responseDetails) {
			var div = parseHtmlResponse(responseDetails.responseText);
			if(!div) return;
			var cmts = getElementByClass('comments_list', div);
			var c = cmts ? cmts.getElementsByTagName('li').length : 0;
			updateTrackedLink(id, c, tracked);
			$state.tracked_new_replies_total += c - getTrackedCount(id);
			$tracked_reloading -= 1;
			if($tracked_reloading == 0) {
				$ui.full.tracked_list = tracked;
				$ui.full.watch_icon.src = $media.watchicon;
				$ui.small.wimg.src = $media.watchicon;
				removeChildren($ui.full.tracked_list_win);
				$ui.full.tracked_list_win.appendChild($ui.full.tracked_list);
				var total = !$state.tracked_new_replies_total ? 0 : $state.tracked_new_replies_total;
				$store.setPrivate($store.tracked_new_replies_total, total);
				update_ui();
			}
		});
	} catch (error) {}
}

function removeChildren(element) {
	if(element.hasChildNodes()) {
		while(element.childNodes.length >= 1) {
			element.removeChild(element.firstChild)
		}
	}
}

//initialize permanent elements of the UI	
function init_ui() {
	//main container
	$ui.main = document.createElement('div');
	$ui.main.style.border = '1px solid gray';
	$ui.main.style.background = 'white';
	$ui.main.style.color = '#003366';
	$ui.main.style.position = 'fixed';
	$ui.main.style.bottom = '0px';
	$ui.main.style.right = '0px';
	$ui.main.style.padding = '4px';
	$ui.main.style.zIndex = 100;
	$ui.main.style.textAlign = 'left';

	////////////
	//small ui window view
	$ui.small.div = document.createElement('div');

	// sg
	
	var a = document.createElement('a');
	a.style.textDecoration = 'none';
	//a.target = '_blank';

	$ui.small.sg = document.createElement('div');
	$ui.small.sg.title = 'Strona główna [pokaż]';
	$ui.small.sg_img = document.createElement('img');
	$ui.small.sg_img.src = $media.sgicon;
	$ui.small.sg_img.style.marginBottom = '5px';
	$ui.small.sg_img.style.border = 'none';
	$ui.small.sg_img.style.marginRight = '2px';
	$ui.small.sg.appendChild($ui.small.sg_img);

	a.appendChild($ui.small.sg);
	a.href = 'http://www.salon24.pl/index.html';

	$ui.small.div.appendChild(a);

	//author's blog new comments
	$ui.small.ablog = document.createElement('div');
	$ui.small.ablog.title = 'nowe komentarze w ostatniej własnej notce [przejdź]';
	$ui.small.ablog_link = document.createElement('a');
	$ui.small.ablog_link.style.textDecoration = 'none';
	$ui.small.himg = document.createElement('img');
	$ui.small.himg.src = $media.homeicon;
	$ui.small.himg.style.border = '0';
	$ui.small.ablog_link.appendChild($ui.small.himg);
	$ui.small.ablog.appendChild($ui.small.ablog_link);
	$ui.small.ablog_text = document.createElement('span');
	$ui.small.ablog_text.style.marginLeft = '5px';
	$ui.small.ablog_link.appendChild($ui.small.ablog_text);
	$ui.small.div.appendChild($ui.small.ablog);

	//number of comments
	$ui.small.comm = document.createElement('div');
	$ui.small.comm.title = 'komentarze do tej notki [pokaż ostatni]';

	$ui.small.comm_img = document.createElement('img');
	$ui.small.comm_img.src = $media.commenticon;
	$ui.small.comm_img.style.marginRight = '5px';

	$ui.small.comm.appendChild($ui.small.comm_img);

	$ui.small.comm_text = document.createElement('span');
	$ui.small.comm.appendChild($ui.small.comm_text);
	$ui.small.comm.style.cursor = 'pointer';

	addEvent($ui.small.comm, 'click', function(e) {
		var postList = getElementByClass('posts_list');
		var pos = findPos(postList);
		window.scroll(0, pos.top - window.innerHeight);
	});

	$ui.small.div.appendChild($ui.small.comm);

	if(!$state.post_id) $ui.small.comm.style.display = 'none';

	//number of new comments among tracked posts
	$ui.small.trep = document.createElement('div');
	$ui.small.trep.title = 'nowe komentarze w subskrybowanych notkach [pokaż listę]';
	$ui.small.wimg = document.createElement('img');
	$ui.small.wimg.src = $media.watchicon;
	$ui.small.wimg.style.marginRight = '5px';
	$ui.small.trep.appendChild($ui.small.wimg);
	$ui.small.trep_text = document.createElement('span');
	$ui.small.trep.appendChild($ui.small.trep_text);
	$ui.small.trep.style.cursor = 'pointer';
	addEvent($ui.small.trep, 'click', function(e) {
		$ui.mode = 1; 
		$ui.trackedmode = 1;
		$store.set('ui_mode', $ui.mode); 
		$store.set('ui_trackedmode', $ui.trackedmode); 
		update_ui();
	});
	$ui.small.div.appendChild($ui.small.trep);

	$ui.small.track = document.createElement('div');
	$ui.small.track.title = '[subskrybuj/odsubskrybuj tę notkę]';
	$ui.small.track_icon = document.createElement('img');
	$ui.small.track_icon.src = $media.untrackedicon;
	$ui.small.track.appendChild($ui.small.track_icon);
	$ui.small.track_s = document.createElement('span');

	//$ui.small.track.style.borderBottom= "solid black 1px";
	$ui.small.track.style.cursor = "pointer";
	addEvent($ui.small.track, 'click', function(e) {
		if(isBeingTracked($state.post_id)) stopTracking($state.post_id);
		else trackThisNote(e);
		showCurrentSubscriptions();
		update_ui();
	});
	$ui.small.div.appendChild($ui.small.track);
	if(!$state.post_id) $ui.small.track.style.display = 'none';

	//switch to full view
	$ui.small.more = document.createElement('div');
	$ui.small.more.style.textAlign = 'right';
	var img = document.createElement('img');
	img.src = $media.plusicon;
	addEvent($ui.small.more, 'click', function(e) { 
		$ui.mode = 1; 
		$store.set('ui_mode', $ui.mode); 
		update_ui(); 
	});
	$ui.small.more.appendChild(img);
	$ui.small.more.style.marginTop = '5px';
	$ui.small.div.appendChild($ui.small.more);

	////////////
	//full ui window view
	$ui.full.div = document.createElement('div');

	// sg
	var div = document.createElement('a');
	div.style.fontSize = 'smaller';
	div.style.textDecoration = 'none';
	div.style.fontStyle = 'italic';
	div.style.cursor = 'pointer';
	//div.target = '_blank';
	div.href = 'http://www.salon24.pl/index.html';

	$ui.full.sg_img = document.createElement('img');
	$ui.full.sg_img.title = 'Strona główna [pokaż]';
	$ui.full.sg_img.src = $media.sgicon;
	$ui.full.sg_img.style.marginBottom = '5px';
	$ui.full.sg_img.style.border = 'none';
	$ui.full.sg_img.style.marginRight = '2px';
	$ui.full.sg_img.style.cssFloat = 'right';

	div.appendChild($ui.full.sg_img);

	$ui.full.sg_div_title = document.createElement('span');
	$ui.full.sg_div_title.style.marginLeft = '5px';
	div.appendChild($ui.full.sg_div_title);

	$ui.full.div.appendChild(div);


	//author's blog new comments
	$ui.full.ablog = document.createElement('div');
	$ui.full.ablog.title = 'nowe komentarze w ostatniej własnej notce [przejdź]';

	$ui.full.ablog_link = document.createElement('a');
	$ui.full.himg = document.createElement('img');
	$ui.full.himg.src = $media.homeicon;
	$ui.full.himg.style.border = '0';
	$ui.full.ablog_link.appendChild($ui.full.himg);
	$ui.full.ablog_link.style.textDecoration = 'none';
	$ui.full.ablog.appendChild($ui.full.ablog_link);
	$ui.full.ablog_text = document.createElement('span');
	$ui.full.ablog_text.style.marginLeft = '5px';
	$ui.full.ablog_link.appendChild($ui.full.ablog_text);
	$ui.full.div.appendChild($ui.full.ablog);

	//number of comments
	$ui.full.comm = document.createElement('div');
	$ui.full.comm.title = 'komentarze do tej notki [pokaż ostatni]';

	$ui.full.comm_img = document.createElement('img');
	$ui.full.comm_img.src = $media.commenticon;
	$ui.full.comm.appendChild($ui.full.comm_img);
	$ui.full.comm_text2 = document.createElement('span');
	$ui.full.comm_text2.style.marginLeft = '5px';
	$ui.full.comm.appendChild($ui.full.comm_text2);
	//$ui.full.comm.style.marginBottom = '5px';
	//$ui.full.comm.style.borderBottom = 'solid black 1px';
	$ui.full.comm.style.cursor = 'pointer';

	addEvent($ui.full.comm, 'click', function(e) {
		var postList = getElementByClass('posts_list');
		var pos = findPos(postList);
		window.scroll(0, pos.top - window.innerHeight);
	});


	$ui.full.div.appendChild($ui.full.comm);
	$ui.full.comm_text1 = document.createElement('span');
	$ui.full.comm.appendChild($ui.full.comm_text1);
	$ui.full.comm_text1.style.marginLeft = '5px';

	if(!$state.post_id) $ui.full.comm.style.display = 'none';

	//list of tracked posts
	$ui.full.trep = document.createElement('div');
	$ui.full.trep_text = document.createElement('span');
	$ui.full.trep.appendChild($ui.full.trep_text);
	$ui.full.div.appendChild($ui.full.trep);


	var tmpdiv = document.createElement('div');
	tmpdiv.title = 'nowe komentarze w subskrybowanych notkach [pokaż/schowaj listę]';
	tmpdiv.style.cursor = 'pointer';

	$ui.full.watch_icon = document.createElement('img');
	$ui.full.watch_icon.src = $media.watchicon;
	$ui.full.watch_icon.style.marginRight = '5px';
	//tmp.style.marginTop = '5px';
	tmpdiv.appendChild($ui.full.watch_icon);

	$ui.full.subcnt_text = document.createElement('span');
	$ui.full.subcnt_text.innerHTML = 'subskrybcje';
	tmpdiv.appendChild($ui.full.subcnt_text);

	$ui.full.div.appendChild(tmpdiv);

	addEvent(tmpdiv, 'click', function(e){
			$ui.trackedmode = !$ui.trackedmode;
			update_ui();
			$store.set('ui_trackedmode', $ui.trackedmode); 
	});

	$ui.full.tracked_list_win = document.createElement('div');
	$ui.full.tracked_list_win.style.fontSize = 'smaller';
	$ui.full.tracked_list_win.style.paddingLeft = '13px';
	$ui.full.tracked_list = document.createElement('div');
	$ui.full.tracked_list_win.appendChild($ui.full.tracked_list);
	$ui.full.div.appendChild($ui.full.tracked_list_win);

	$ui.full.track = document.createElement('div');
	$ui.full.track.title = '[subskrybuj/odsubskrybuj tę notkę]';
	$ui.full.track_icon = document.createElement('img');
	$ui.full.track_icon.src = $media.untrackedicon;
	$ui.full.track_icon.style.marginRight = '5px';
	$ui.full.track.appendChild($ui.full.track_icon);
	$ui.full.track_text = document.createElement('span');
	$ui.full.track.appendChild($ui.full.track_text);

	$ui.full.track.style.cursor = "pointer";
	addEvent($ui.full.track, 'click', function(e) {
		if(isBeingTracked($state.post_id)) stopTracking($state.post_id);
		else trackThisNote(e);
		showCurrentSubscriptions();
		update_ui();
	});
	$ui.full.div.appendChild($ui.full.track);
	if(!$state.post_id) $ui.full.track.style.display = 'none';


	//configuration & small view switch
	$ui.full.less = document.createElement('div');
	$ui.full.less.style.textAlign = 'right';
	var img = document.createElement('img');
	img.src = $media.configicon;
	addEvent(img, 'click', function(e) { showConfig(); });
	$ui.full.less.appendChild(img);

	
	img = document.createElement('img');
	img.src = $media.minusicon;
	img.style.marginLeft = '4px';
	addEvent(img, 'click', function(e) { 
			$ui.mode = 0; 
			$store.set('ui_mode', $ui.mode); 
			update_ui(); 
	});
	$ui.full.less.appendChild(img);
	$ui.full.div.appendChild($ui.full.less);

	$ui.full.less.style.marginTop = '5px';

	document.body.appendChild($ui.main);	

	$ui.blocker = document.createElement('div');
	$ui.blocker.style.height = document.body.offsetHeight;
	$ui.blocker.style.width = '100%';
	$ui.blocker.style.background = 'white';
	$ui.blocker.style.color = 'black';
	$ui.blocker.style.position = 'absolute';
	$ui.blocker.style.top = '0px';
	$ui.blocker.style.left = '0px';
	$ui.blocker.style.opacity = '0.5';
	$ui.blocker.style.zIndex = '150';
	$ui.blocker.style.display = 'none';

	document.body.appendChild($ui.blocker);
} 

function update_ui() {
  if(!$ui.main) 
		init_ui();

	//remove actual view
	removeChildren($ui.main);

  	var tracked = isBeingTracked($state.post_id);
	var login = GM_getValue($store.login);

	var new_replies = $store.getPrivate($store.my_last_unread_cmts);
	var new_tracked_replies = $store.getPrivate($store.tracked_new_replies_total);
	
	if($ui.mode==0) {
		//(re)add small view
		$ui.small.track_icon.src = isBeingTracked($state.post_id)? $media.trackedicon : $media.untrackedicon;
		$ui.main.appendChild($ui.small.div);

		// sg
		var ncnt = GM_getValue($sg_new_count);

		if(ncnt > 0) $ui.small.sg_img.style.border = 'solid red 1px';
		else $ui.small.sg_img.style.border = 'none';

		//number of comments in current document
		$ui.small.comm_text.innerHTML = $state.comments;
		if($state.comments_updating)
			$ui.small.comm_img.src= $media.throbbericon;
		else
			$ui.small.comm_img.src = $media.commenticon;

		//number of _new_ comments in the last post of author's blog
		if(login) {
			$ui.small.ablog_link.href = 'http://' + login + '.salon24.pl/';
			$ui.small.ablog_text.innerHTML = new_replies;
			if(new_replies > 0)
				$ui.small.ablog_text.style.color = 'red';
			else
				$ui.small.ablog_text.style.color = '';
			$ui.small.ablog.style.display = 'block';
		} else {
			$ui.small.ablog.style.display = 'none';
		}

		//number of new replies in tracked posts
		$ui.small.trep_text.innerHTML = new_tracked_replies;
	}
	else if($ui.mode==1) {
		//(re)add full view
		if(isBeingTracked($state.post_id)) {
			$ui.full.track_icon.src = $media.trackedicon;
			$ui.full.track_text.innerHTML = 'odsubskrybuj';
		} else {
			$ui.full.track_icon.src = $media.untrackedicon;
			$ui.full.track_text.innerHTML = 'subskrybuj';
		}
		$ui.main.appendChild($ui.full.div);

		//sg
		var title = GM_getValue($sg_first_title);
		var ncnt = GM_getValue($sg_new_count);

		var len = getParam($sg_first_title_length, 30);
		if(title) {
			if(title.length > len)
				$ui.full.sg_div_title.innerHTML = title.slice(0, len) + '...';
			else
				$ui.full.sg_div_title.innerHTML = title;
		}

		if(ncnt > 0) $ui.full.sg_img.style.border = 'solid red 1px';
		else $ui.full.sg_img.style.border = 'none';

		//number of comments in current document
		var min = $state.comments_update_time.getMinutes() < 10 ? '0'+$state.comments_update_time.getMinutes() : $state.comments_update_time.getMinutes();
		$ui.full.comm_text1.innerHTML = "&ndash; stan na " + $state.comments_update_time.getHours() + ':' + min + ' ';
		$ui.full.comm_text2.innerHTML = $state.comments;
		if($state.comments_updating)
			$ui.full.comm_img.src= $media.throbbericon;
		else
			$ui.full.comm_img.src = $media.commenticon;

		//number of _new_ comments in the last post of author's blog
		if(login) {
			//TODO: not true
			$ui.full.ablog_link.href = 'http://' + login + '.salon24.pl/';
			$ui.full.ablog_text.innerHTML = login + ": " + new_replies;
			if(new_replies > 0)
				$ui.full.ablog_text.style.color = 'red';
			else
				$ui.full.ablog_text.style.color = '';
			$ui.full.ablog.style.display = 'block';
			$ui.full.subcnt_text.innerHTML =  "subskrypcje (" + new_tracked_replies +")";
		} else 
			$ui.full.ablog.style.display = 'none';

		$ui.full.tracked_list.style.display = $ui.trackedmode ? 'block' : 'none'; 
		$ui.full.sg_div_title.style.display = $ui.trackedmode ? "block" : 'none';
		//TODO: make it stay on the right... no idea how to do this right now.
		$ui.full.sg_img.style.cssFloat = $ui.trackedmode ? "right": "none";
	}
}

function toggleUI() {
	var mode = GM_getValue('ui_mode');
	$ui.mode = mode ? 0 : 1;
	$store.set('ui_mode', $ui.mode); 
	update_ui();
}

function toggleSubscriptions() {

	if(GM_getValue('ui_mode') == 0) {
		$store.set('ui_mode', 1);
		$ui.mode = 1;
	}

	$ui.trackedmode = !$ui.trackedmode;
	update_ui();
	$store.set('ui_trackedmode', $ui.trackedmode); 
	update_ui();
}

function checkSG() {
	$ui.full.sg_img.src = $media.throbbericon; 
	$ui.small.sg_img.src = $media.throbbericon;
	loadPage('http://www.salon24.pl/index.html', updateSGInfo);
}

function updateSGInfo(responseData) {
	var div = parseHtmlResponse(responseData.responseText);
	var data = getSGData(div);
	var list = data.list;

	var old = GM_getValue($sg_post_list);

	if(!old) { 
		$store.set($sg_new_count, list.length);
		$store.set($sg_first_title, data.first_title);
		update_ui();
		$ui.full.sg_img.src = $media.sgicon;
		$ui.small.sg_img.src = $media.sgicon;
		return;
	}

	old = old.split($X);

	var newPosts = [];
	for (var i=0;i<list.length;i++) {
		if(contains(old, list[i])) continue;
		newPosts[newPosts.length] = list[i];
	}

	$store.set($sg_new_count, newPosts.length);
	$store.set($sg_first_title, data.first_title);
	update_ui();
	$ui.full.sg_img.src = $media.sgicon;
	$ui.small.sg_img.src = $media.sgicon;
}

function getSGData(div) {
	var tmp = getElementsByClass('bdL', div)[1];
	var posts = tmp.getElementsByTagName('h2');
	var first = tmp.getElementsByTagName('h1')[0].getElementsByTagName('a')[0];

	var list = [first.href];
	for(var i=0;i<posts.length;i++) {
		var a = posts[i].getElementsByTagName('a')[0];
		if(i==29) break;

		list[list.length] = a.href;
	}
	return {"list": list, 'first_title' : first.innerHTML};
}

function doRememberSG() {
	var data = getSGData(document.body);
	var list = data.list;

	$store.set($sg_post_list, list.join($X));
	$store.set($sg_new_count, 0);
	$store.set($sg_first_title, data.first_title);
}

function contains(arr, el) {
	for(var i=0;i<arr.length;i++) if(arr[i] == el) return true;
	return false;
}

function init() {
	if(isIframe()) return;
	try {
		$trueWindow = unsafeWindow;
	} catch (error) {
		$trueWindow = window;
	}

	if(!isLoggedIn()) clearLoginInfo();
	
	setup();

	if(!isLoggedIn()) return;

	getLoginInfo();

	window.addEventListener('mousemove', mousemove, true);
}

//TODO: make this work - now user can missclick link, should be obvious what is being clicked.
addGlobalStyle('.glink:hover { color: red; } ');

window.addEventListener('focus', onWindowFocus, true);
window.addEventListener('blur', onWindowBlur, true);
window.addEventListener('keypress', keypressed, true);
window.addEventListener('load', init, true);
